Reputation: 141
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 -
P.S. I know there are countless similar questions on StackOverflow, but none of them worked for me and I've been struggling for weeks.
Upvotes: 0
Views: 1772
Reputation: 141
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.Headers.Add(HttpRequestHeader.Accept, "application/octet-stream");
// Download the file
webClient.DownloadFileAsync(downloadUrl, "C:/Path/To/File.zip");
Upvotes: 2