C# example of downloading GitHub private repo programmatically

前端 未结 4 1120
广开言路
广开言路 2020-12-16 17:10

I see that the download path for a GitHub repo is of the form

https://github.com/{username}/{reponame}/archive/{branchname}.zip

For a priva

相关标签:
4条回答
  • 2020-12-16 17:42

    Here is a pure C# way:

    var githubToken = "[token]";
    var url = "https://github.com/[username]/[repository]/archive/[sha1|tag].zip";
    var path = @"[local path]";
    
    using (var client = new System.Net.Http.HttpClient())
    {
        var credentials = string.Format(System.Globalization.CultureInfo.InvariantCulture, "{0}:", githubToken);
        credentials = Convert.ToBase64String(System.Text.Encoding.ASCII.GetBytes(credentials));
        client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", credentials);
        var contents = client.GetByteArrayAsync(url).Result;
        System.IO.File.WriteAllBytes(path, contents);
    }
    
    0 讨论(0)
  • 2020-12-16 17:44

    with CURL:

    curl -L -F "login=$USER" -F "token=$TOKEN" https://github.com/$USER/$REPO/$PKGTYPE/$BRANCHorTAG
    

    where $TOKEN is the API token on your github profile, not an oAuth2 token used for communicating with the APIv3.

    $USER is the user account the token is connected with, not necessarily the organization/other user the repo belongs to. Second Instance of $USER is the user/account the repo is.

    $REPO is the name of the private repository

    $PKGTYPE is tarball or zipball and $BRANCHorTAG is a branch, like master, or a tag name for a commit.

    The first instance of $USER must have access to the repo belonging to the second instance of $USER.

    I could not find this documented ANYWHERE, so I also have a little write up about it if you want anything more detailed.

    0 讨论(0)
  • 2020-12-16 18:00

    See this guide on creating a personal access token then run the following:

    var githubToken = "token";
    var request = (HttpWebRequest)WebRequest.Create("https://api.github.com/repos/$OWNER/$REPO/contents/$PATH");
    request.Headers.Add(HttpRequestHeader.Authorization, string.Concat("token ", githubToken));
    request.Accept = "application/vnd.github.v3.raw";
    request.UserAgent = "test app"; //user agent is required https://developer.github.com/v3/#user-agent-required
    using (var response = request.GetResponse())
    {
        var encoding = System.Text.ASCIIEncoding.UTF8;
        using (var reader = new System.IO.StreamReader(response.GetResponseStream(), encoding))
        {
            var fileContent = reader.ReadToEnd();
        }
    }
    
    0 讨论(0)
  • 2020-12-16 18:04

    I'm looking into the Okctokit.Net currently. Give it a shot. NuGet: Install-Package Octokit

    0 讨论(0)
提交回复
热议问题