C#WebClient DownloadProgressChanged将无法正常工作

Rob*_*arb 6 .net c# webclient file download

我正在尝试使用WebClient对象的DownloadDataAsync方法使用C#从Internet下载文件.

我还想通过使用webclient对象的DownloadProgressChanged事件来获取下载进度.

问题是,BytesReceived和TotalBytesToReceive属性都没有显示正确的值.当我在调试时尝试检查它们时,它们都以不可复制的方式发生变化.

我的代码:

WebClient client = new WebClient();
        client.BaseAddress = this.DownloadUrl;
        client.DownloadProgressChanged += downloadProgressDelegate;
        client.DownloadDataAsync(new System.Uri(this.DownloadUrl));
Run Code Online (Sandbox Code Playgroud)

ulr*_*chb 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();
Run Code Online (Sandbox Code Playgroud)

......并得到以下结果:

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

似乎工作.

编辑:也许你的HTTP服务器没有正确返回大小,但我没有一个URI来测试这个服务器行为的WebClient实现.