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

发布于 2025-01-27 20:58:36 字数 251 浏览 4 评论 0原文

我有以下代码

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

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

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

为你拒绝所有暧昧 2025-02-03 20:58:36

httpclient上的文档的最佳来源当然是Microsoft网站本身:
https:// https://learlearn.microsoft.com/en-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);
}

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);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文