Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/288.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# (); contentResponse.Dispose(); 文件数据; data.name=file.name; data.contents=内容; 结果.文件.添加(数据); } } 返回结果; } } }_C#_Git_Github_Http Status Code 404_Token - Fatal编程技术网

C# (); contentResponse.Dispose(); 文件数据; data.name=file.name; data.contents=内容; 结果.文件.添加(数据); } } 返回结果; } } }

C# (); contentResponse.Dispose(); 文件数据; data.name=file.name; data.contents=内容; 结果.文件.添加(数据); } } 返回结果; } } },c#,git,github,http-status-code-404,token,C#,Git,Github,Http Status Code 404,Token,}问题是令牌没有足够的权限,一旦我授予了正确的权限,它就工作得很好 您在请求中使用的实际URL是什么?您在浏览器中尝试过吗?这是一个私人回购协议,您将无法看到它,是的,我可以从浏览器中打开它,我创建了“刚刚读取”权限令牌,但仍然无法,是否需要授予更多权限? using GitHubRepoGrabber.GithubClient; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Octokit; using System; usi

}

问题是令牌没有足够的权限,一旦我授予了正确的权限,它就工作得很好

您在请求中使用的实际URL是什么?您在浏览器中尝试过吗?这是一个私人回购协议,您将无法看到它,是的,我可以从浏览器中打开它,我创建了“刚刚读取”权限令牌,但仍然无法,是否需要授予更多权限?
using GitHubRepoGrabber.GithubClient;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Octokit;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;

namespace GitHubRepoGrabber{
class Program
{
    static void Main(string[] args)
    {

        //try 1
        var task = Github.getRepo("owner", "repo", "token");
        task.Wait();
        var dir = task.Result;

        //try 2
        Task.Factory.StartNew(async () =>
        {
            var repoOwner = "owner";
            var repoName = "name";
            var path = "path";

            var httpClientResults = await ListContents(repoOwner, repoName, path);
            PrintResults("From HttpClient", httpClientResults);

            var octokitResults = await ListContentsOctokit(repoOwner, repoName, path);
            PrintResults("From Octokit", octokitResults);

        }).Wait();
        Console.ReadKey();
    }
    static async Task<IEnumerable<string>> ListContents(string repoOwner, string repoName, string path)
    {
        using (var client = GetGithubHttpClient())
        {
            var resp = await client.GetAsync($"repos/{repoOwner}/{repoName}/contents/{path}");
            var bodyString = await resp.Content.ReadAsStringAsync();
            var bodyJson = JToken.Parse(bodyString);
            return bodyJson.SelectTokens("$.[*].name").Select(token => token.Value<string>());
        }
    }

    static async Task<IEnumerable<string>> ListContentsOctokit(string repoOwner, string repoName, string path)
    {
        var client = new GitHubClient(new Octokit.ProductHeaderValue("Github-API-Test"));
        // client.Credentials = ... // Set credentials here, otherwise harsh rate limits apply.

        var contents = await client.Repository.Content.GetAllContents(repoOwner, repoName, path);
        return contents.Select(content => content.Name);
    }

    private static HttpClient GetGithubHttpClient()
    {
        return new HttpClient
        {
            BaseAddress = new Uri("https://api.github.com"),
            DefaultRequestHeaders =
        {
            // NOTE: You'll have to set up Authentication tokens in real use scenario
            // NOTE: as without it you're subject to harsh rate limits.
            {"User-Agent", "Github-API-Test"}
        }
        };
    }

    static void PrintResults(string source, IEnumerable<string> files)
    {
        Console.WriteLine(source);
        foreach (var file in files)
        {
            Console.WriteLine($" -{file}");
        }
    }   }namespace GithubClient
{
    //JSON parsing methods
    struct LinkFields
    {
        public String self;
    }
    struct FileInfo
    {
        public String name;
        public String type;
        public String download_url;
        public LinkFields _links;
    }

    //Structs used to hold file data
    public struct FileData
    {
        public String name;
        public String contents;
    }
    public struct Directory
    {
        public String name;
        public List<Directory> subDirs;
        public List<FileData> files;
    }

    //Github classes
    public class Github
    {
        //Get all files from a repo
        public static async Task<Directory> getRepo(string owner, string name, string access_token)
        {
            HttpClient client = new HttpClient();
            Directory root = await readDirectory("root", client, String.Format("https://api.github.com/repos/{0}/{1}/contents/", owner, name), access_token);
            client.Dispose();
            return root;
        }

        //recursively get the contents of all files and subdirectories within a directory 
        private static async Task<Directory> readDirectory(String name, HttpClient client, string uri, string access_token)
        {
            //get the directory contents
            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, uri);
            request.Headers.Add("Authorization",
                "Basic " + Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(String.Format("{0}:{1}", access_token, "x-oauth-basic"))));
            request.Headers.Add("User-Agent", "lk-github-client");

            //parse result
            HttpResponseMessage response = await client.SendAsync(request);
            String jsonStr = await response.Content.ReadAsStringAsync(); ;
            response.Dispose();
            FileInfo[] dirContents = JsonConvert.DeserializeObject<FileInfo[]>(jsonStr);

            //read in data
            Directory result;
            result.name = name;
            result.subDirs = new List<Directory>();
            result.files = new List<FileData>();
            foreach (FileInfo file in dirContents)
            {
                if (file.type == "dir")
                { //read in the subdirectory
                    Directory sub = await readDirectory(file.name, client, file._links.self, access_token);
                    result.subDirs.Add(sub);
                }
                else
                { //get the file contents;
                    HttpRequestMessage downLoadUrl = new HttpRequestMessage(HttpMethod.Get, file.download_url);
                    downLoadUrl.Headers.Add("Authorization",
                        "Basic " + Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(String.Format("{0}:{1}", access_token, "x-oauth-basic"))));
                    request.Headers.Add("User-Agent", "lk-github-client");

                    HttpResponseMessage contentResponse = await client.SendAsync(downLoadUrl);
                    String content = await contentResponse.Content.ReadAsStringAsync();
                    contentResponse.Dispose();

                    FileData data;
                    data.name = file.name;
                    data.contents = content;

                    result.files.Add(data);
                }
            }
            return result;
        }
    }
}