2011-02-12 108 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(); 

上述两种方法各有利弊,它是由你来把他们的其中之一。