Ajit Hegde
Ajit Hegde

Reputation: 552

How to make progressbar for downloading string using webclient in wpf..?

I made a small application which helps to download html contents of webpages. I made progressbar and I cant get any values or any change using webclient downloadprogress changed event handler. Here is my code..

private void Window_Loaded(object sender, RoutedEventArgs e)
{
    progressBar1.Maximum = 100;
    WebClient wb = new WebClient();
    wb.DownloadProgressChanged += new DownloadProgressChangedEventHandler(wb_DownloadProgressChanged);
    wb.DownloadStringCompleted += new DownloadStringCompletedEventHandler(wb_DownloadStringCompleted);
    wb.DownloadStringAsync(new Uri("http://www.google.com"));
}

void wb_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
    string htmldoc = e.Result;
}

void wb_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
    progressBar1.Value = e.ProgressPercentage;
}

When I run this code e.progresspercentage is always 0 and when download completes it become 100. So I cant make progressbar workable. Can somebody tell me what is wrong here..? Thanks in advance.

Upvotes: 0

Views: 3192

Answers (3)

Peter Lillevold
Peter Lillevold

Reputation: 33930

Not sure about this but I suspect the DownloadXXX methods relies on the total size being reported upfront in order to report progress. Just like a passive FTP download will not report the total download size upfront, perhaps google.com web server is not returning the appropriate headers indicating the expected amount of bytes that will be sent down the pipe.

Upvotes: 1

Milan Solanki
Milan Solanki

Reputation: 1207

According to the documentation, DownloadStringAsync does not report progress. See the documentation of the WebClient.DownloadProgressChanged Event.

Also you want to use

using System.ComponentModel;

client.DownloadStringCompleted += new AsyncCompletedEventHandler(client_DownloadFileCompleted);

Upvotes: 0

Tim S.
Tim S.

Reputation: 56556

You can't, DownloadStringAync doesn't raise the DownloadProgressChanged event. You could use DownloadDataAsync instead, then translate it to a string, using something like System.Text.Encoding, as mentioned here.

Upvotes: 1

Related Questions