简体   繁体   中英

Download asset from private GitHub repository release with Octokit.net

I am trying to download the latest asset from my private github repo, but every single time I get a 404 error, here is my code:

// Initializes a GitHubClient
GitHubClient client = new GitHubClient(new ProductHeaderValue("MyClient"));
client.Credentials = new Credentials("my-token");

// Gets the latest release
Release latestRelease = client.Repository.Release.GetLatest("owner", "repo").Result;
string downloadUrl = latestRelease.Assets[0].BrowserDownloadUrl;

// Download with WebClient
using var webClient = new WebClient();
webClient.Headers.Add(HttpRequestHeader.UserAgent, "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36");
webClient.Headers.Add(HttpRequestHeader.Authorization, $"token {my-token}");

webClient.DownloadFileAsync(new Uri(downloadUrl), @"F:\Path\For\Storing\My\File.zip");
// this line creates the .zip file, but is always 0KB

I've tried -

  • Adding "Accept: application/octet-stream" header;
  • Using "username:password" as authorization header;
  • (BAD IDEA, NEVER DO THIS!!!) Granting full scopes to the token and none of them worked.

PS I know there are countless similar questions on StackOverflow, but none of them worked for me and I've been struggling for weeks.

So I finally figured it out. You should use the GitHub REST Api to download the file, instead of the direct link.

GET /repos/owner/repository/releases/assets/<asset_id>

The following is the updated code:

// Initializes a GitHubClient
GitHubClient client = new GitHubClient(new ProductHeaderValue("MyClient"));
client.Credentials = new Credentials("my-token");

// Gets the latest release
Release latestRelease = client.Repository.Release.GetLatest("owner", "repo").Result;
int assetId = latestRelease.Assets[0].Id;
string downloadUrl = $"https://api.github.com/repos/owner/repository/releases/assets/{assetId}";

// Download with WebClient
using var webClient = new WebClient();
webClient.Headers.Add(HttpRequestHeader.UserAgent, "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36");
webClient.Headers.Add(HttpRequestHeader.Authorization, "token my-token");
webClient.Heasers.Add(HttpRequestHeader.Accept, "application/octet-stream");

// Download the file
webClient.DownloadFileAsync(downloadUrl, "C:/Path/To/File.zip");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM