ReadAsync从缓冲区获取数据

时间:2014-08-03 13:24:32

标签: 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, 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,但这显然是错误的。在这个漫长的周日下午,我感激不尽。

2 个答案:

答案 0 :(得分:11)

下载的内容位于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();
  }
}

答案 1 :(得分:1)

您阅读的数据应位于buffer数组中。实际上是数组的起始bytesRead个字节。检查MSDN上的ReadAsync方法。