我想从GET HTTP REQUEST响应中下载文件。要下载流,我使用HttpClient
就像这个示例:
using System.Net.Http;
using System.Net.Http.Headers;
using ModernHttpClient;
var exClient = new HttpClient(new NativeMessageHandler());
var request = new HttpRequestMessage(new HttpMethod(method), "https://speed.hetzner.de/10GB.bin");
HttpResponseMessage response = await exClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
var contentStream = await response.Content.ReadAsStreamAsync();
我想将文件保存到磁盘,所以我使用System.IO
。
首先,我使用以下代码:
using IOFile = System.IO.File;
Stream file = IOFile.Open(path, FileMode.Create);
contentStream.CopyTo(file);
file.close;
但是我也想获取有关下载进度的信息,所以我切换到以下代码:
using IOFile = System.IO.File;
Stream file = IOFile.Open(path, FileMode.Create);
var buffer = new byte[81920];
int received = 0;
int read = 0;
while ((read = await contentStream.ReadAsync(buffer, 0, buffer.Length)) > 0)
{
file.Write(buffer, 0, read);
received += read;
//progressCallback?.Invoke(received);
}
file.Close();
我的问题是下载时间变得比使用CopyTo
方法的时间长两倍以上(大约30Mbit / s,而CopyTo约为90)。
什么解释了这种差异?我该如何接近CopyTo的表现?