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

1 c# webclient dotnet-httpclient

我有以下代码

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

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

Edm*_*ppe 7

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

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);
}
Run Code Online (Sandbox Code Playgroud)