private void DownloadFile() {
if (_downloadUrls.Any()) {
WebClient client = new WebClient();
client.DownloadProgressChanged += client_DownloadProgressChanged;
client.DownloadFileCompleted += client_DownloadFileCompleted;
var url = _downloadUrls.Dequeue();
string startTag = "animated/";
string endTag = "/infra";
int index = url.IndexOf(startTag);
int index1 = url.IndexOf(endTag);
string fname = url.Substring(index + 9, index1 - index - 9);
client.DownloadFileAsync(new Uri(url), @"C:\Temp\tempframes\" + fname + ".gif");
lastDownloadedFile = @"C:\Temp\tempframes\" + fname + ".gif";
label1.Text = url;
return;
}
// End of the download
btnStart.Text = "Download Complete";
}
private void client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e) {
if (e.Error != null) {
// handle error scenario
throw e.Error;
}
if (e.Cancelled) {
// handle cancelled scenario
}
Image img = new Bitmap(lastDownloadedFile);
Image[] frames = GetFramesFromAnimatedGIF(img);
foreach(Image image in frames) {
countFrames++;
image.Save(@"C:\Temp\tempframes\" + countFrames + ".gif");
}
DownloadFile();
}
void client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e) {
double bytesIn = double.Parse(e.BytesReceived.ToString());
double totalBytes = double.Parse(e.TotalBytesToReceive.ToString());
double percentage = bytesIn/totalBytes * 100;
pBarFileProgress.Value = int.Parse(Math.Truncate(percentage).ToString());
label1.Text = e.BytesReceived.ToString() + "/" + e.TotalBytesToReceive.ToString();
}
現在我加入這個方法如何計算並顯示每個文件的下載速度?
DateTime lastUpdate;
long lastBytes = 0;
private void progressChanged(long bytes) {
if (lastBytes == 0) {
lastUpdate = DateTime.Now;
lastBytes = bytes;
return;
}
var now = DateTime.Now;
var timeSpan = now - lastUpdate;
var bytesChange = bytes - lastBytes;
var bytesPerSecond = bytesChange/timeSpan.Seconds;
lastBytes = bytes;
lastUpdate = now;
}
而且我想用這種方法或另一種方法在LABEL2的progresschanged事件顯示下載速度。但我不確定如何使用這種方法。
不確定如何在progresschanged事件中使用它。
一般來說'每秒字節數=最後一個數據包中的字節數/自上一個數據包以來的秒數',以便看起來正確。平滑一點(例如通過保持最後10個值並顯示平均值),並獲得下載速度。 –
@ManfredRadlwimmer如果你能告訴我該怎麼做?謝謝。 –
當然,我會舉一個簡短的例子,馬上回來。 –