Search code examples
c#webclientdotnet-httpclient

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

  • The best source of documentation on HttpClient is, of course, the Microsoft site itself: https://learn.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://learn.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);
    }