ReadAsync从缓冲区获取数据

本文关键字:数据 获取 缓冲区 ReadAsync | 更新日期: 2023-09-27 18:16:05

我已经想了一段时间了(我知道这很傻)。

我正在下载一个显示良好的进度条文件,但我如何从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);
    }
  }
}

我试图通过结果变量,但这显然是错误的。在这个漫长的周日下午,如果有人能指点我,我将不胜感激。

ReadAsync从缓冲区获取数据

下载的内容位于byte[] buffer变量中:

int bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length);

From Stream.ReadAsync:

缓冲:

类型:系统。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方法