Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# WebClient DownloadProgressChanged won't work properly

I'm trying to Download a File from the Internet with C# by using the DownloadDataAsync Method of an WebClient Object.

I also want to get the downloading progress by using the DownloadProgressChanged event of the webclient object.

The problem is, neither the BytesReceived nor the TotalBytesToReceive properties are showing up correct values. They are both changing in an irreproducible way when I try to check them while debugging.

My code:

WebClient client = new WebClient();
        client.BaseAddress = this.DownloadUrl;
        client.DownloadProgressChanged += downloadProgressDelegate;
        client.DownloadDataAsync(new System.Uri(this.DownloadUrl));
like image 203
Robert Harb Avatar asked Feb 12 '11 12:02

Robert Harb


2 Answers

I just tried the following code in 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();

... and got the following result:

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

Seems to work.

EDIT: Maybe your HTTP server doesn't return the size correctly, but I don't have an URI to test this server behavior against the WebClient implementation.

like image 137
ulrichb Avatar answered Oct 04 '22 20:10

ulrichb


Had similar problems, right after DownloadDataAsync try:

while (client.IsBusy) { Application.DoEvents(); }
like image 31
Hasenpriester Avatar answered Oct 04 '22 20:10

Hasenpriester