Downloading a file is a common task, and it is often useful to run this potentially time-consuming operation on a separate thread. Use the BackgroundWorker component to accomplish this task with very little code.
First Create a New Windows forms application, and then Add Textbox, Button, progress bar and BackgroundWorker Controls to that Form. Also add a FolderBrowserDialog Control for Select the folder to save Downloaded File.
The following code example demonstrates how to use a BackgroundWorker component to download file from a URL. When the user clicks the Download button, the Click event handler opens a Folder Browsing Dialogue box, after selecting the Folder the RunWorkerAsync method of a BackgroundWorker component to start the download operation. The button is disabled for the duration of the download, and then enabled when the download is complete. A Message Box displays the Result of Downloading.
First, we have to Enter the URL into text box for Download a File
URL like this:
The btnDownload_Click Event Method opens dialogue box to select a Folder for saving the downloaded file.
private void btnDownload_Click(object sender, EventArgs e)
if (txtAddress.Text == "")
MessageBox.Show("Please Enter URL To Download File.");
Set the BackgroundWorker's properties like this:
Go to the Events view of the BackgroundWorker and double click each of its events so they are auto-wired up as shown here:
Double click the button to auto-wire up the event click event and call our background worker to start running asynchronously when the button is clicked. Your code will look something like this:
Now implement the BackgroundWorker's ProgressChanged event to update the progress bar.
Here's the code:
private void bgWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
progressBar1.Value = e.ProgressPercentage;
For convenience, in the result you can show a message that your file is downloaded to note that it is completely finished like this:
private void bgWorker1_RunWorkerCompleted(object sender,RunWorkerCompletedEventArgs e)
if (status == true)
MessageBox.Show("File Download Compleated..");
MessageBox.Show("FILE Not Downloaded");
btnDownload.Enabled = true;
txtAddress.Text = "";