使用 WebClient 或 HttpClient 下载文件?

编程入门 行业动态 更新时间:2024-10-28 21:24:15
本文介绍了使用 WebClient 或 HttpClient 下载文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试从 URL 下载文件,我必须在 WebClient 和 HttpClient 之间进行选择.我参考了这篇文章和互联网上的其他几篇文章.由于 HttpClient 强大的异步支持和其他 .Net 4.5 特权,在任何地方都建议使用 HttpClient.但我仍然不完全相信,需要更多的投入.

I am trying to download file from a URL and I have to choose between WebClient and HttpClient. I have referenced this article and several other articles on the internet. Everywhere, it is suggested to go for HttpClient due to its great async support and other .Net 4.5 privileges. But I am still not totally convinced and need more inputs.

我正在使用以下代码从互联网下载文件:

I am using below code to download file from internet:

网络客户端:

WebClient client = new WebClient(); client.DownloadFile(downloadUrl, filePath);

HttpClient:

using (HttpClient client = new HttpClient()) { using (HttpResponseMessage response = await client.GetAsync(url)) using (Stream streamToReadFrom = await response.Content.ReadAsStreamAsync()) { } }

从我的角度来看,我只能看到使用 WebClient 的一个缺点,那就是非异步调用,阻塞了调用线程.但是如果我不担心线程阻塞或者使用 client.DownloadFileAsync() 来利用异步支持呢?

From my perspective, I can see only one disadvantage in using WebClient, that would be the non async call, blocking the calling thread. But what if I am not worried about the blocking of thread or use client.DownloadFileAsync() to leverage the async support?

另一方面,如果我使用 HttpClient,我是不是将文件的每个字节都加载到内存中,然后将其写入本地文件?如果文件太大,内存开销会不会很贵?如果我们使用 WebClient 可以避免这种情况,因为它会直接写入本地文件而不消耗系统内存.

On the other hand, if I use HttpClient, ain't I loading every single byte of a file into memory and then writing it to a local file? If the file size is too large, won't memory overhead be expensive? Which could be avoided if we use WebClient, since it will directly write to local file and not consume system memory.

那么,如果性能是我的首要任务,我应该使用哪种方法进行下载?如果我的上述假设是错误的,我想澄清一下,我也愿意接受替代方法.

So, if performance is my utter priority, which approach should I use for download? I would like to be clarified if my above assumption is wrong, and I am open to alternate approach as well.

推荐答案

您可以使用 .Net 4.5+ 本地完成.我试着按照你的方式去做,然后我在 Intellisense 中找到了一种似乎有意义的方法.

You can do it natively with .Net 4.5+. I tried doing it your way and then I just found a method in Intellisense that seemed to make sense.

docs.microsoft/en-us/dotnet/api/system.io.stream.copytoasync?view=netframework-4.7.2

uri = new Uri(generatePdfsRetrieveUrl + pdfGuid + ".pdf"); HttpClient client = new HttpClient(); var response = await client.GetAsync(uri); using (var fs = new FileStream( HostingEnvironment.MapPath(string.Format("~/Downloads/{0}.pdf", pdfGuid)), FileMode.CreateNew)) { await response.Content.CopyToAsync(fs); }

更多推荐

使用 WebClient 或 HttpClient 下载文件?

本文发布于:2023-11-02 13:17:14,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1552505.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文件   WebClient   HttpClient

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!