[英]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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.