如何在 .NET 中使用 HttpClient 而不是 WebClient 下载 Excel 文件?

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

我有以下代码

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

所以我的问题是,如何使用 HttpClient 而不是 WebClient 下载 Excel 文件?

关于 HttpClient 的最佳文档来源当然是 Microsoft 站点本身: https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclient 这是我用于下载电子表格的代码的(过于简化的)版本:

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);
}