'How to download Excel file with HttpClient instead of WebClient in .NET?

I have the following code

private void SaveFile(string linkToFile, string filename)
{
    using WebClient client = new();
    client.DownloadFile(linkToFile, ResourcePath + filename);
}

So my question is, how can I download Excel file with HttpClient instead of WebClient?



Solution 1:[1]

The best source of documentation on HttpClient is, of course, the Microsoft site itself: https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclient Here's an (oversimplified) version of the code I use for downloading spreadsheets:

private async Task SaveFile(string fileUrl, string pathToSave)
{
    // See https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclient
    // for why, in the real world, you want to use a shared instance of HttpClient
    // rather than creating a new one for each request
    var httpClient = new HttpClient();
    
    var httpResult = await httpClient.GetAsync(fileUrl);
    using var resultStream = await httpResult.Content.ReadAsStreamAsync();
    using var fileStream = File.Create(pathToSave);
    resultStream.CopyTo(fileStream);
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1