20 Mar 2012

File Downloading with progress bar using Background Worker Class In C#

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:

private void bgWorker1_DoWork(object sender, DoWorkEventArgs e)


     string sUrlToDnldFile = txtAddress.Text;

     string sFileSavePath;



        Uri url = new Uri(sUrlToDnldFile);

        string sFileName = Path.GetFileName(url.LocalPath);

        sFileSavePath = folderBrowserDialog1.SelectedPath.ToString()+"\\" + sFileName;

        System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);

         System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse();


         // gets the size of the file in bytes

         long iSize = response.ContentLength;


        // keeps track of the total bytes downloaded so we can update the progress bar

        long iRunningByteTotal = 0;

        WebClient client = new WebClient();

        Stream strRemote = client.OpenRead(url);

        FileStream strLocal = new FileStream(sFileSavePath, FileMode.Create, FileAccess.Write, FileShare.None);

         int iByteSize = 0;

        byte[] byteBuffer = new byte[1024];

         while ((iByteSize = strRemote.Read(byteBuffer, 0, byteBuffer.Length)) > 0)


             // write the bytes to the file system at the file path specified

            strLocal.Write(byteBuffer, 0, iByteSize);

                    iRunningByteTotal += iByteSize;

              // calculate the progress out of a base "100"

              double dIndex = (double)(iRunningByteTotal);

              double dTotal = (double)iSize;

              double dProgressPercentage = (dIndex / dTotal);

               int iProgressPercentage = (int)(dProgressPercentage * 100);

                    // update the progress bar




                status = true;


            catch (Exception exM)


            //Show if any error Occured

                MessageBox.Show("Error: " + exM.Message);

                status = false;


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 = "";

For Downloading the entire solution file CLICK HERE
For Downloading the Set Up file for this application CLICK HERE