Robert Harb
Robert Harb

Reputation: 61

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));

Upvotes: 6

Views: 4537

Answers (3)

user3578181
user3578181

Reputation: 1979

You should simply "await" it. I.e.:

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

Please don't forget to convert your method into an "async Task", async Task or async void. Otherwise if you don't want to make changes in your method signiture you can also do the following:

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

Both the above approaches have advantages and disadvantages and it's up to you to take which one of them.

Upvotes: -1

Hasenpriester
Hasenpriester

Reputation: 451

Had similar problems, right after DownloadDataAsync try:

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

Upvotes: 1

ulrichb
ulrichb

Reputation: 20054

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.

Upvotes: 5

Related Questions