Giovanni Savoretti
Giovanni Savoretti

Reputation: 11

C#: 404 error when downloading an asset from GitHub

I wanted to tell you about the problem I encountered trying to download a release file (https://github.com/OWNER/REPO/releases/download/TAG/FILE) from a private GitHub repository. When I try to download the file I get the error:

Response status code does not indicate success: 404 (Not Found).

Used packages:

using Newtonsoft.Json.Linq;                                   
using System.IO;                                              
using System.Net.Http;                                        
using System.Net.Http.Headers;

Code:

string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
using HttpClient client = new();
client.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("Pippo", "2.3"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("token", V.token);
try
{
    string releaseUrl = $"https://api.github.com/repos/{V.owner}/{V.repoName}/releases/latest";
    HttpResponseMessage response = await client.GetAsync(releaseUrl);
    response.EnsureSuccessStatusCode();
    string jsonResponse = await response.Content.ReadAsStringAsync();
    JObject release = JObject.Parse(jsonResponse);
    MessageBox.Show($"Release: {release["name"]}");
    var assets = release["assets"];
    foreach (var asset in assets)
    {
        string assetName = asset["name"].ToString();
        string downloadUrl = asset["browser_download_url"].ToString();
        MessageBox.Show($"Downloading: {assetName}");
        string filePath = Path.Combine(desktopPath, assetName);
        using HttpResponseMessage assetResponse = await client.GetAsync(downloadUrl);
        assetResponse.EnsureSuccessStatusCode();
        byte[] fileBytes = await assetResponse.Content.ReadAsByteArrayAsync();
        await File.WriteAllBytesAsync(filePath, fileBytes);
        MessageBox.Show($"Downloaded: {assetName} in {filePath}");
    }
}
catch (Exception ex)
{
    MessageBox.Show($"Error: {ex.Message}");
}

I am sure the token is right because it shows me MessageBox, which is only possible with authentication.

I tried downloading another file from a different reposity, this time a public one, and.... I succeeded.

I could not find any solution, and since I have seen many with the same problem, I opened this thread.

I thank anyone who can give me a hand!

Upvotes: 0

Views: 41

Answers (0)

Related Questions