我需要下载二进制文件并在到达时访问原始数据。
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 = ?
}
或者,写入流也会有所帮助。我也不介意使用其他下载方法,主要目标是即时阅读下载。
答案 0 :(得分:0)
您可以按照SørenLorentzen的建议使用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++;
}
}
}
}
}