2011-11-30 85 views
1

所以基本上我有一個下載文件的窗​​體,名爲file.jpg,每小時旋轉一次,例如,我有一個按鈕開始下載,隨機下載它的任意數量時間(主要是這是一個自學習練習)我喜歡添加代碼正在進行更改,我想以某種方式獲取隨時間收到的字節以獲取kb/s。我搜索了一下,找不到任何東西。我不需要任何花哨的網絡堆棧,因爲它們是標準的JPEG文件,所以它不是太大(事實上,當文件下載的時候,當我清除進度條時,我從來沒有看到它開始...但我離題了)我喜歡看到avg kb/s,即使我看到它2秒(文件大約每個說1兆)。任何幫助深表感謝。在ProgressChanged中計算下載速度

private void btnStart_Click(object sender, EventArgs e) 
    { 
     btnStart.Enabled = false; 
     btnStop.Enabled = true; 



     WebClient webclient = new WebClient();   
     webclient.DownloadFileCompleted += new AsyncCompletedEventHandler(Completed); 
     webclient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChanged);    
     // you need to increment the number !!! 

     // add the file to the list. 
     // single click should preview 
     // progress bar should clear after it downloads 
     // the status bar as well should be done 

     int num = nextIndex() + 1; 
     string file = @"C:\IMG\IMG_"; 
     file += string.Format("{0:d5}", num); 
     file += ".jpg"; 

     webclient.DownloadFileAsync(new Uri("http://www.foobar.com/file.jpg"), file); 
     lstFiles.Enabled = false;   
    } 

private void ProgressChanged(object sender, DownloadProgressChangedEventArgs e) 
    { 
     // display kb/sec as well?? 
     pbDownload.Value = e.ProgressPercentage; 

    } 

回答

1
private void downloadMyWorkProgress(object sender, DownloadProgressChangedEventArgs e) 
{ 
    double bytesIn = double.Parse(e.BytesReceived.ToString()); 
    double totalBytes = double.Parse(e.TotalBytesToReceive.ToString()); 
    double percentage = bytesIn/totalBytes * 100; 
    progressBar1.Value = int.Parse(Math.Truncate(percentage).ToString()); 
} 
+0

如果以上的答案是爲你工作不是請接受作爲一個答案。 –