【发布时间】:2014-08-03 22:18:40
【问题描述】:
一段时间以来,我一直在琢磨这个问题(并且知道这很愚蠢)。
我正在下载带有显示正常的 ProgressBar 的文件,但是如何从 ReadAsync 流中获取数据以保存?
public static readonly int BufferSize = 4096;
int receivedBytes = 0;
int totalBytes = 0;
WebClient client = new WebClient();
byte[] result;
using (var stream = await client.OpenReadTaskAsync(urlToDownload))
{
byte[] buffer = new byte[BufferSize];
totalBytes = Int32.Parse(client.ResponseHeaders[HttpResponseHeader.ContentLength]);
for (;;)
{
result = new byte[stream.Length];
int bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length);
if (bytesRead == 0)
{
await Task.Yield();
break;
}
receivedBytes += bytesRead;
if (progessReporter != null)
{
DownloadBytesProgress args =
new DownloadBytesProgress(urlToDownload, receivedBytes, totalBytes);
progessReporter.Report(args);
}
}
}
我尝试通过结果变量,但这显然是错误的。在这个漫长的周日下午,我将不胜感激。
【问题讨论】:
-
我认为您需要另一个流来将文件(缓冲区)保存到磁盘。
-
你的缓冲区的内容是什么?内容在您的
byte[] buffer变量中 -
好吧,你没有使用
result。result不可能包含您的数据,因为流甚至不知道该变量的存在。 (我感觉你在这里有一些误解。不确定是什么。) -
是的。它会创建一个长度正确的文件,其中没有数据。
标签: c#