C# 从DownloadDataAsync检索部分下载的字节块

C# 从DownloadDataAsync检索部分下载的字节块,c#,download,C#,Download,我需要下载一个二进制文件,并在原始数据到达时访问它 private void Downloadfile(string url) { WebClient client = new WebClient(); client.DownloadDataCompleted += DownloadDataCompleted; client.DownloadProgressChanged += DownloadProgressCallback;

我需要下载一个二进制文件,并在原始数据到达时访问它

    private void Downloadfile(string url)
    {
        WebClient client = new WebClient();
        client.DownloadDataCompleted += DownloadDataCompleted;
        client.DownloadProgressChanged += DownloadProgressCallback;
        client.DownloadDataAsync(new Uri(url));
    }

    public void DownloadProgressCallback(object sender, DownloadProgressChangedEventArgs e)
    {
        long bytes = e.BytesReceived;
        long total = e.TotalBytesToReceive;
        int progress = e.ProgressPercentage;
        string userstate = (string)e.UserState;
        byte[] received = ?
    }

或者,向流中写入也会有所帮助。我也不介意使用另一种下载方法,主要目标是动态阅读下载

您可以使用Søren Lorentzen建议的
WebClient.OpenRead

    using (var client = new WebClient())
    using (var stream = client.OpenRead(address))       
    {
        byte[] readBuffer = new byte[4096];

        int totalBytesRead = 0;
        int bytesRead;

        while ((bytesRead = stream.Read(readBuffer, totalBytesRead, readBuffer.Length - totalBytesRead)) > 0)
        {
            totalBytesRead += bytesRead;

            if (totalBytesRead == readBuffer.Length)
            {
                int nextByte = stream.ReadByte();
                if (nextByte != -1)
                {
                    byte[] temp = new byte[readBuffer.Length];
                    Buffer.BlockCopy(readBuffer, 0, temp, 0, readBuffer.Length);
                    Buffer.SetByte(temp, totalBytesRead, (byte)nextByte);
                    readBuffer = temp;
                    totalBytesRead++;
                }
            }
        }
   }

}

如果需要,您可以尝试使用
WebClient.OpenRead
。等等,为什么要创建大小为readBuffer.Length*2的临时数组?不需要,只需删除它。我没有从自定义实现中正确清理代码。