我正在尝试使用 Webclient 对象以每个 5% 的块下载数据。原因是我需要报告每个下载块的进度。
这是我为执行此任务而编写的代码:
private void ManageDownloadingByExtractingContentDisposition(WebClient client, Uri uri)
{
//Initialize the downloading stream
Stream str = client.OpenRead(uri.PathAndQuery);
WebHeaderCollection whc = client.ResponseHeaders;
string contentDisposition = whc["Content-Disposition"];
string contentLength = whc["Content-Length"];
string fileName = contentDisposition.Substring(contentDisposition.IndexOf("=") +1);
int totalLength = (Int32.Parse(contentLength));
int fivePercent = ((totalLength)/10)/2;
//buffer of 5% of stream
byte[] fivePercentBuffer = new byte[fivePercent];
using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.ReadWrite))
{
int count;
//read chunks of 5% and write them to file
while((count = str.Read(fivePercentBuffer, 0, fivePercent)) > 0);
{
fs.Write(fivePercentBuffer, 0, count);
}
}
str.Close();
}
问题 - 当它到达 str.Read() 时,它会暂停读取整个流,然后计数为 0。所以 while() 不起作用,即使我指定只读取五百分变量。看起来它在第一次尝试时读取了整个流。
我怎样才能使它正确读取块?
谢谢,
安德烈