c# – ReadAsync从缓冲区获取数据

前端之家收集整理的这篇文章主要介绍了c# – 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,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:

buffer:

Type: System.Byte[]
The buffer to write the data into.

你永远不会使用你的结果变量.不确定为什么它在那里.

编辑

所以问题是如何阅读流的完整内容.您可以执行以下操作:

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();
  }
}
原文链接:/csharp/100704.html

猜你在找的C#相关文章