Add this using statement to the top of the form.
using System.Net;
private void btnStartDownload_Click(object sender, EventArgs e)
{
WebClient client = new WebClient();
client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged);
client.DownloadFileCompleted += new AsyncCompletedEventHandler(client_DownloadFileCompleted);
// Starts the download
client.DownloadFileAsync(new Uri("SomeURLToFile"), "SomePlaceOnLocalHardDrive");
btnStartDownload.Text = "Download In Process";
btnStartDownload.Enabled = false;
}
In the previous code, we are creating two event handlers to handle when
the Progress of the file download changes, and when the download
completes.
We also use the DownloadFileAsync method so that the download(which could be lengthy) does not freeze the main GUI.
Next, we need to do the code to calculate the percentage of the download complete so that we can assign it to the ProgressBar.
void client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
double bytesIn = double.Parse(e.BytesReceived.ToString());
double totalBytes = double.Parse(e.TotalBytesToReceive.ToString());
double percentage = bytesIn / totalBytes * 100;
progressBar1.Value = int.Parse(Math.Truncate(percentage).ToString());
}
In this code, we use the BytesReceived and TotalBytesToReceive properties of the DownloadProgressChangedEventArgs object.
Next, we need to do the code for the event when the download completes.
void client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
{
MessageBox.Show("Download Completed");
btnStartDownload.Text = "Start Download";
btnStartDownload.Enabled = true;
}