c# – ReadAsync从缓冲区获取数据
发布时间:2020-12-15 08:06:02 所属栏目:百科 来源:网络整理
导读:一段时间以来,我一直在敲打这个问题(并且知道这是愚蠢的事情). 我正在下载带有ProgressBar的文件,它显示正常,但我如何从ReadAsync流中获取数据以保存? public static readonly int BufferSize = 4096;int receivedBytes = 0;int totalBytes = 0;WebClient c
一段时间以来,我一直在敲打这个问题(并且知道这是愚蠢的事情).
我正在下载带有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,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 []缓冲区变量中:
int bytesRead = await stream.ReadAsync(buffer,buffer.Length); 来自Stream.ReadAsync:
你永远不会使用你的结果变量.不确定为什么它在那里. 编辑 所以问题是如何阅读流的完整内容.您可以执行以下操作: 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,buffer.Length)) > 0) { ms.Write(buffer,read); receivedBytes += read; if (progessReporter != null) { DownloadBytesProgress args = new DownloadBytesProgress(urlToDownload,totalBytes); progessReporter.Report(args); } } return ms.ToArray(); } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |