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

时间:2019-09-27 15:32:50

标签: c# .net github-api

下面是一个示例,说明了如何从控制台应用程序访问公共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),似乎对我使用的githubtoken的任何使用都返回403或404。我的令牌已读取:packages和read:repo_hook,我认为就足够了。我使用以下link向我展示了如何创建令牌。我需要其他任何东西来访问带有令牌的私人仓库吗?

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

1 个答案:

答案 0 :(得分:1)

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

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

感谢Olivier Rogier为我提供了线索