2011-02-12 96 views
6

我正在嘗試使用WebClient對象的DownloadDataAsync方法通過C#從網上下載文件,即 。C#WebClient DownloadProgressChanged將無法正常工作

我也想通過使用webclient對象的DownloadProgressChanged事件來獲取下載進度。

問題是,BytesReceived和TotalBytesToReceive屬性都沒有顯示正確的值。當我試圖在調試時檢查它們時,它們都以不可重現的方式變化。

我的代碼:

WebClient client = new WebClient(); 
     client.BaseAddress = this.DownloadUrl; 
     client.DownloadProgressChanged += downloadProgressDelegate; 
     client.DownloadDataAsync(new System.Uri(this.DownloadUrl)); 
+1

你下載了什麼文件?您能否從本地IIS中以帶寬有限的方式嘗試一個大文件,以提供可重複的測試環境? – 2011-02-12 12:25:04

回答

5

我只是想下面的代碼在LINQPad:

var uri = @"http://download.services.openoffice.org/files/stable/3.3.0/OOo_3.3.0_Win_x86_install-wJRE_en-US.exe"; 

WebClient client = new WebClient(); 
client.DownloadProgressChanged += (sender, e) => 
    { 
    Console.WriteLine("Bytes: " + e.BytesReceived + " of " + e.TotalBytesToReceive); 
    }; 

client.DownloadDataAsync(new System.Uri(uri)); 

Thread.Sleep(4000); 
client.CancelAsync(); 

...,得到了以下結果:

 
Bytes: 4138 of 158067944 
Bytes: 50858 of 158067944 
Bytes: 68378 of 158067944 
Bytes: 134078 of 158067944 
Bytes: 133914 of 158067944 
..... 

似乎工作。

編輯:也許你的HTTP服務器不正確return the size,但我沒有一個URI,以測試對WebClient執行這一服務器行爲。

+0

它可能取決於正在下載的文件嗎? – 2011-02-12 12:37:05

1

過類似的問題,之後DownloadDataAsync嘗試:

while (client.IsBusy) { Application.DoEvents(); } 
0

您應該簡單地 「等待」 了。 I.e .:

await client.DownloadDataAsync(new System.Uri(uri)); 

請不要忘記將您的方法轉換爲「異步任務」,異步任務或異步無效。否則,如果你不想讓你的方法signiture的變化也可以做到以下幾點:

client.DownloadDataAsync(new System.Uri(uri)).Wait(); 

上述兩種方法各有利弊,它是由你來把他們的其中之一。