从DownloadDataAsync检索部分下载的字节块
本文关键字:字节 下载 DownloadDataAsync 检索部 | 更新日期: 2023-09-27 18:25:20
我需要下载一个二进制文件,并在到达时访问原始数据。
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++;
}
}
}
}
}