Reputation: 3211
I am using the WebClient
class to download an .exe file from a web server. Here is the code I am using to download the file:
WebClient webClient = new WebClient();
webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(webClient_DownloadProgressChanged);
webClient.DownloadDataAsync(new Uri("http://www.blah.com/calc.exe"));
My application has a ProgressBar which gets updated in the callback (webClient_DownloadProgressChanged
):
private void webClient_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
progressBar.Value = (int)e.BytesReceived;
}
The problem I am having is I have to set the Maximum
value for the progress bar dynamically. In other words I need to know the size of the file I am downloading before the download starts.
Is there a way to get the size of a file (before downloading it) given it's uri?
Upvotes: 3
Views: 3688
Reputation: 239
If you only need to update progress bar correctly, the easiest way is to use ProgressPercentage
// progressBar.Max is always set to 100
progressBar.Value = e.ProgressPercentage;
Upvotes: 2
Reputation: 442
Try to set max size to e.TotalBytesToReceive like this
private void webClient_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
progressBar.Max = (int)e.TotalBytesToReceive;
progressBar.Value = (int)e.BytesReceived;
}
Upvotes: 5
Reputation: 26307
One of the ways will be checking for the Content-Length or the Range header in ResponseHeaders.
// To set the range
//webClient.Headers.Add("Range","bytes=-128");
// To read Content-Length
var bytes = Convert.ToInt64(webClient.ResponseHeaders["Content-Length"]);
Upvotes: 2