1

I'm coding an application that will download files one at a time, it all works fine so far, but I ran into some problems once I tried to make my progressbar display the progress of the download. I've done it before, but this is the first time I'm doing all of this on a backgroundworker thread. The reason I'm using DownloadFile instead of DownloadFileAsync is because I need it to download the files one at a time, and I found doing it this way was a bit easier.

This is a part of the code:

    private void button1_Click(object sender, EventArgs e)
    {
        BackgroundWorker bw = new BackgroundWorker();

        bw.DoWork += bw_DoWork;
        bw.ProgressChanged += bw_ProgressChanged;
        bw.RunWorkerCompleted += bw_RunWorkerCompleted;
        bw.WorkerReportsProgress = true;

        if (!bw.IsBusy)
        {
            bw.RunWorkerAsync();
        }


    }

    void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        MessageBox.Show("Patching Completed.");
    }

    void bw_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
        barPatch.Value = e.ProgressPercentage;
    }

    void bw_DoWork(object sender, DoWorkEventArgs e)
    {
        doPatch();

    }

    private void doPatch()
    {

        for (int C = int.Parse(File.ReadAllText("Client.txt")); C < S; C++)
        {
            this.lblC.InvokeEx(lbl => lblC.Text = Convert.ToString(C + 1));
            wc.DownloadFile(String.Format("http://localhost:1234/Launcher/Patches/{0}.zip", C + 1), String.Format("{0}.zip", C + 1));
            File.WriteAllText("Client.txt", Convert.ToString(C + 1));
        }
    }

    void wc_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
    {


    }

Any help is appreciated! Thanks

2 Answers 2

0

You can use wc.DownloadFileAsync instead of wc.DownloadFile

And in wc_DownloadProgressChanged use

bw.ReportProgress(e.BytesReceived / e.TotalBytesToReceive * 100);

You can visit

WebClient.DownloadProgressChanged Event

And

BackgroundWorker.ReportProgress Method (Int32)

For more help.

3
  • The thing is, I don't want to use Async since it attempts to download all of the files at once. I know that it's possible to make a queue, but I just thought that using DownloadFile on a backgroundworker would be less time consuming. Jun 30, 2014 at 2:31
  • @GrantWinney Yeah I tried doing that, but nothing happened. Could it be because the webclient is doing it's work on a different thread, and the DownloadProgressChanged only affects that thread and not the UI one? Jun 30, 2014 at 2:54
  • I think if you tried to use DownloadFileAsync at new thread it will work as DownloadFile Jun 30, 2014 at 21:30
0

A VERY dirty trick but you can get progress of any filesize changing if you do this:

        class InfoForDownload
        {
              public string FileName {get; set;}
              public int FileSize {get; set;}
        }

        int fileSizeFromCheck;

        InfoForDownload info = new InfoForDownload() { FileName = "C:\Users\TheUser\OneDrive\Documents\etc\etc\backup.sql", FileSize = THEFILESIZEOFTHEFILEONEXTERNAL };

        BackgroundWorker checkDownload = new BackgroundWorker();
        checkDownload.WorkerReportsProgress = true;
        checkDownload.ProgressChanged += checkDownload_ProgressChanged;
        checkDownload.DoWork += checkDownload_DoWork;
        checkDownload.RunWorkerAsync(info);

        void downloadWorker_DoWork(object sender, DoWorkEventArgs e)
        {
              BackgroundWorker checkDownload = (sender as BackgroundWorker);
              if (e.Argument != null)
              {
                    InfoForDownload info = (sender as InfoForDownload);
                    ProcessStartInfo cmdStartInfo = new ProcessStartInfo();
                    cmdStartInfo.FileName = @"C:\Windows\System32\cmd.exe";
                    cmdStartInfo.RedirectStandardOutput = true;
                    cmdStartInfo.RedirectStandardError = true;
                    cmdStartInfo.RedirectStandardInput = true;
                    cmdStartInfo.UseShellExecute = false;
                    cmdStartInfo.CreateNoWindow = true;

                    while(info.FileSize > fileSizeFromCheck){
                          Process cmdProcess = new Process();
                          cmdProcess.StartInfo = cmdStartInfo;
                          cmdProcess.ErrorDataReceived += cmd_Error;
                          cmdProcess.OutputDataReceived += cmd_DataReceived;
                          cmdProcess.EnableRaisingEvents = true;
                          cmdProcess.Start();
                          cmdProcess.BeginOutputReadLine();
                          cmdProcess.BeginErrorReadLine();
                          cmdProcess.StandardInput.WriteLine("for %I in (info.FileName) do @echo %~zI");
                          cmdProcess.StandardInput.WriteLine("exit");
                          cmdProcess.WaitForExit();
                          Thread.Sleep(200);
                          Console.WriteLine("The size of the file is " + fileSizeFromCheck + " " + (info.FileSize / fileSizeFromCheck  * 100) + "%");
                          checkDownload.ReportProgress(info.FileSize / fileSizeFromCheck  * 100);
                    }

              }
        }

        void checkDownload_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
              progressBar.Value = e.ProgressPercentage;
        }

        static void cmd_DataReceived(object sender, DataReceivedEventArgs e)
        {
              Console.WriteLine("Output from other process");
              Console.WriteLine(e.Data);
              Int32.TryParse((e.Data / 1024) / 1024, out fileSizeFromCheck);
        }

Make the edits to fit your use and a progressbar named progressBar. Voila. Dirty as dirty can be.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.