我正嘗試使用WebClient對象以5%的塊爲單位下載數據。原因是我需要爲每個下載的塊報告進度。WebClient.OpenRead以塊爲單位下載數據
這裏是我寫的做這個任務的代碼:
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()不起作用,即使我指定只讀取5Percent變量。它看起來像在第一次嘗試中讀取整個流。
我該如何使它正確讀取塊?
感謝,
安德烈
註冊WebClient.DownloadProgressChanged事件,然後調用WebClient.DownloadDataAsync()。您可以更新事件回調中的進度。 – Jon