Emin
Emin

Reputation: 13

how to use progressbar for process of downloading

I want to use progress bar in my windows form application. The application will used for downloading a file from a directory to another directory.

But application seem like doing nothing when the user click the download button. So I want to show process of downloanding with progress bar to the user.

I did search for progress bar but I could not find answer of "how to use progress bar for process of downloading".

I would be very pleased if someone explain to me how to use progress bar for process of downloading.

Upvotes: 1

Views: 6673

Answers (2)

Sara
Sara

Reputation: 121

You can use DownloadFileAsync to download file without blocking the main thread and set also an event handler to show the progress in the bar:

  private void button1_Click(object sender, EventArgs e)
    {
        WebClient webClient = new WebClient();
        string sourceFile = @"\\server\test.txt";
        string destFile = @"\\server2\test2.txt";
        webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(DownloadCompleted);
        webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChanged);
        webClient.DownloadFileAsync(new Uri(sourceFile), destFile);
    }

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

    private void DownloadCompleted(object sender, AsyncCompletedEventArgs e)
    {
        MessageBox.Show("The download is completed!");
    }

Or another approach can be using a BackgroundWorker with the property WorkerReportsProgress set to true. Then you should subscribe the events DoWork and ProgressChanged: in the DoWork method you put the code to download or transmit the file on a separated thread and to calculate the progress of the work. In the ProgressChanged method just update the progress bar value. In this case your code will look like this:

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {
        // the path of the source file
        string sourceFile = @"\\shared\test.txt";
        // the path to write the file to
        string destFile = @"\\shared2\test2.txt";

        FileInfo info = new FileInfo(sourceFile);
        // gets the size of the file in bytes
        Int64 size = info.Length;
        // keeps track of the total bytes downloaded so you can update the progress bar
        Int64 runningByteTotal = 0;
        using (FileStream reader = new FileStream(sourceFile, FileMode.Open, FileAccess.Read))
        {
            using (Stream writer = new FileStream(destFile, FileMode.Create, FileAccess.Write, FileShare.None))
            {
                int iByteSize = 0;
                byte[] byteBuffer = new byte[size];
                while ((iByteSize = reader.Read(byteBuffer, 0, byteBuffer.Length)) > 0)
                {
                    // write the bytes to the file
                    writer.Write(byteBuffer, 0, iByteSize);
                    runningByteTotal += iByteSize;
                    // calculate the progress
                    double index = (double)(runningByteTotal);
                    double total = (double)byteBuffer.Length;
                    double progressPercentage = (index / total);
                    int iProgressPercentage = (int)(progressPercentage * 100);
                    // update the progress bar
                    backgroundWorker1.ReportProgress(iProgressPercentage);
                }
                // clean up the file stream
                writer.Close();
            }

        }
    }

private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
        progressBar1.Value = e.ProgressPercentage;
    }

In the button click event (or whatever) that triggers the downloading of the file, you should add this code to start the background worker running asynchronously:

private void button1_Click(object sender, EventArgs e)
    {
        backgroundWorker1.RunWorkerAsync();
    }

Upvotes: 4

a-ctor
a-ctor

Reputation: 3733

The WebClient has a DownloadProgressChanged-Event. Hook it up to the progress bar and you are good to go. MSDN

Remark: You need to use DownloadDataAsync, DownloadFileAsync or OpenReadAsync for the DownloadProgressChanged-Event to fire.

Upvotes: 0

Related Questions