2009-07-10 26 views
3

我有一個小應用程序,從遠程(HTTP)服務器下載一些文件到用戶本地硬盤驅動器,一些文件很大,但我不知道運行時有多大。有什麼方法可以讓我用某種類型的進度表下載文件嗎?從網上下載文件到本地文件與進度計在C#

這是一個WinForms應用程序,現在我正在使用WebClient.DownloadFile()來下載文件。

編輯: 我查看了DownloadProgressChanged和OnDownloadProgressChanged事件,它們似乎工作正常,但它們不適用於我的解決方案。我正在下載多個文件,如果我使用WebClient.DownloadFileAsync,則會每秒調用一次該事件,因爲每個文件都會調用它。
這裏是應用程序的基本結構:

  • 下載的文件列表通常約爲114
  • 運行在文件列表中選擇一個循環,並下載每一個到其desination

我不介意分開下載每個文件,但不用DownloadFileAsync()下載它們我不能使用事件處理程序。

回答

5

使用WebClient.OnDownloadProgressChanged。請記住,如果服務器預先報告了大小,則只能計算進度。

編輯:

看你的更新,你可以嘗試正在URL的queue什麼。然後,當一個文件完成下載(DownloadDataCompleted事件)時,您將啓動隊列中下一個URL的異步下載。我沒有測試過這個。

+0

OnDownloadProgressChanged是一種方法,不會幫助OP。它所做的就是在我的回答中引發DownloadProgressChanged事件。捕捉事件是需要的。 – stevehipwell 2009-07-10 08:14:41

+2

我認爲你很挑剔,Stevo。是的,抓住這個事件是必需的,我從來沒有說過。 – 2009-07-10 08:22:43

+0

你永遠不會使用OnDownloadProgressChanged,所有的操作需要做的就是捕捉一個事件。 OnDownloadProgressChanged只是混淆了這個問題。 – stevehipwell 2009-07-10 08:28:55

1

我剛剛寫了這個,它肯定會做你想做的。

另外,在ProgressChanged事件中,您已獲得「TotalBytesToReceive」屬性和「BytesReceived」屬性。

private void StartDownload() 
{ 

    // Create a new WebClient instance. 
    WebClient myWebClient = new WebClient(); 

    // Set the progress bar max to 100 for 100% 
    progressBar1.Value = 0; 
    progressBar1.Maximum = 100; 

    // Assign the events to capture the progress percentage 
    myWebClient.DownloadDataCompleted+=new DownloadDataCompletedEventHandler(myWebClient_DownloadDataCompleted); 
    myWebClient.DownloadProgressChanged+=new DownloadProgressChangedEventHandler(myWebClient_DownloadProgressChanged); 

    // Set the Uri to the file you wish to download and fire it off Async 
    Uri uri = new Uri("http://external.ivirtualdocket.com/update.cab"); 
    myWebClient.DownloadFileAsync(uri, "C:\\Update.cab"); 

} 

void myWebClient_DownloadProgressChanged(object sender, System.Net.DownloadProgressChangedEventArgs e) 
{ 
    progressBar1.Value = e.ProgressPercentage; 
} 

void myWebClient_DownloadDataCompleted(object sender, DownloadDataCompletedEventArgs e) 
{ 
    progressBar1.Value = progressBar1.Maximum; 
} 
1

我需要解決類似的問題,GenericTypeTea的代碼示例沒有辦法;除了在調用DownloadFileAsync方法時發現DownloadDataCompleted事件未被觸發。相反,將引發DownloadFileCompleted事件。

相關問題