ReadAsync从缓冲区获取数据
一段时间以来,我一直在敲打这个问题(并且知道这是愚蠢的事情)。
我正在下载带有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); } } }
我试图通过结果var,但这显然是错误的。 在这个漫长的周日下午,我会感激不尽。
下载的内容位于byte[] buffer
变量中:
int bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length);
来自Stream.ReadAsync
:
缓冲:
类型:System.Byte []将数据写入的缓冲区。
你永远不会使用你的result
变量。 不确定为什么它在那里。
编辑
所以问题是如何阅读流的完整内容。 您可以执行以下操作:
public static readonly int BufferSize = 4096; int receivedBytes = 0; WebClient client = new WebClient(); using (var stream = await client.OpenReadTaskAsync(urlToDownload)) using (MemoryStream ms = new MemoryStream()) { var buffer = new byte[BufferSize]; int read = 0; totalBytes = Int32.Parse(client.ResponseHeaders[HttpResponseHeader.ContentLength]); while ((read = await stream.ReadAsync(buffer, 0, buffer.Length)) > 0) { ms.Write(buffer, 0, read); receivedBytes += read; if (progessReporter != null) { DownloadBytesProgress args = new DownloadBytesProgress(urlToDownload, receivedBytes, totalBytes); progessReporter.Report(args); } } return ms.ToArray(); } }
您读取的数据应该在buffer
数组中。 实际上是数组的开始bytesRead
字节。 检查MSDN上的ReadAsync方法。