从 C# 访问私有 GitHub 存储库中的文件

Access a file from Private GitHub Repository from C#

下面是一个示例,说明我如何从控制台应用程序访问 public GitHub 存储库中的单个文件。我可以为私有存储库做同样的事情吗?我不确定如何更改代码,或者我是否需要使用不同的授权设置来访问它。

谁能告诉我我做错了什么?

我不确定这是否有帮助 https://developer.github.com/v3/guides/managing-deploy-keys/

    private static void Main(string[] args)
    {
        var file = $"https://raw.githubusercontent.com/{username}/{repositoryName}/{branch}/{filePath}";

        System.IO.File.WriteAllText($"c:\{filePath}", GetFile(file));

        System.Console.ReadKey();
    }

    public static string GetFile(string input)
    {
        var output = string.Empty;
        HttpWebRequest request = (HttpWebRequest)System.Net.WebRequest.Create(input);

        request.Headers.Add("Authorization", githubtoken);
        request.AllowAutoRedirect = true;

        var response = (HttpWebResponse)request.GetResponse();

        using (var stream = new System.IO.MemoryStream())
        {
            response.GetResponseStream().CopyTo(stream);
            output = System.Text.Encoding.ASCII.GetString(stream.ToArray());
        }

        response.Close();

        return output;
    }

编辑:

所以根据反馈(感谢 Olivier),似乎我使用 returns 的 githubtoken 的任何使用都是 403 或 404。我的令牌有 read:packages & read:repo_hook 和我认为这就足够了。我使用以下 link 来展示如何创建令牌。我还需要其他任何东西来使用令牌访问私人仓库吗?

我可以通过用户名和密码访问此文件吗?如果可以,我如何更改以上内容以获取文件?

我之前在尝试访问该文件时拥有 read:packagesread:repo_hook 权限,但缺少 repo 权限。一旦提供并重新运行上面的内容,它就开始工作了

我还必须将 url 更改为 https://api.github.com/repositories/{repositoryId}/contents/{filePath} 并且在尝试获得响应之前必须将 request.UserAgent = githubUsername; 添加到请求中

感谢Olivier Rogier给我线索

将权限header更改为:

request.Headers.Add("Authorization", "token " + githubtoken);