我试图从URL下载文件,我必须在WebClient和HttpClient之间进行选择.我在互联网上引用了这篇文章和其他几篇文章.无处不在,由于其非常好的异步支持和其他.Net 4.5权限,建议使用HttpClient.但我仍然不完全相信并需要更多的投入.
我使用下面的代码从互联网上下载文件:
Web客户端:
WebClient client = new WebClient();
client.DownloadFile(downloadUrl, filePath);
Run Code Online (Sandbox Code Playgroud)
HttpClient的:
using (HttpClient client = new HttpClient())
{
using (HttpResponseMessage response = await client.GetAsync(url))
using (Stream streamToReadFrom = await response.Content.ReadAsStreamAsync())
{
}
}
Run Code Online (Sandbox Code Playgroud)
从我的角度来看,我只能看到使用WebClient的一个缺点,那就是非异步调用,阻塞调用线程.但是,如果我不担心阻塞线程或使用client.DownloadFileAsync()异步支持,该怎么办?
另一方面,如果我使用HttpClient,是不是我将文件的每个字节加载到内存中然后将其写入本地文件?如果文件太大,内存开销不会很贵吗?如果我们使用WebClient可以避免这种情况,因为它将直接写入本地文件而不会消耗系统内存.
那么,如果性能是我的首要任务,我应该使用哪种方法进行下载?如果我的上述假设是错误的,我想澄清一下,我也愿意接受替代方法.
在我的一个asp.net Web应用程序中,我需要隐藏正在向用户提供的pdf文件的位置.
因此,我正在编写一种方法,从CMS系统上的位置检索其二进制内容,然后将字节数组刷新到Web用户.
不幸的是,我在下载流时遇到错误:"无法打开文件,因为它已被删除"(或类似于在adobe reader中打开文件时).
问题1:我做错了什么?问题2:我可以使用这种方法下载大文件吗?
private void StreamFile(IItem documentItem)
{
//CMS vendor specific API
BinaryContent itemBinaryContent = documentItem.getBinaryContent();
//Plain old .NET
Stream fileStream = itemBinaryContent.getContentStream();
var len = itemBinaryContent.getContentLength();
SendStream(fileStream, len, itemBinaryContent.getContentType());
}
private void SendStream(Stream stream, int contentLen, string contentType)
{
Response.ClearContent();
Response.ContentType = contentType;
Response.AppendHeader("content-Disposition", string.Format("inline;filename=file.pdf"));
Response.AppendHeader("content-length", contentLen.ToString());
var bytes = new byte[contentLen];
stream.Read(bytes, 0, contentLen);
stream.Close();
Response.BinaryWrite(bytes);
Response.Flush();
}
Run Code Online (Sandbox Code Playgroud)