Click here to Skip to main content
15,912,578 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
Hi there,
I´m trying to create a simple multi-download-application but I´ve got a small problem with assigning a DownloadProgressChangedEvent to a certain progressbar.

I´m using this code to create the needed webclients, etc:

C#
for (int z = 0; z < CheckedCount; z++)
{
    _MultipleWebClients = new WebClient();


    _MultipleWebClients.DownloadFileCompleted += new AsyncCompletedEventHandler(_DownloadFileCompleted);
    _MultipleWebClients.DownloadProgressChanged += new System.Net.DownloadProgressChangedEventHandler(_DownloadProgressChanged);
    _MultipleWebClients.DownloadFileAsync(new Uri(_downloadUrlList[z].ToString()), @"F:\test" + z + ".mp4");
    richTextBox1.AppendText(_downloadUrlList[z].ToString());
}


To display the downloadprogress, I´m using a datagridview with predefined filenames, urls and with a progressbar in each row (with this code).

Now I really don´t know how to assign each DownloadProgressChangedEvent individually, so that each progressbar is showing the correct downloadprogress.

Right now, all progressbars are showing the same percentage, probably because, with my code, they´re all using the same downloadevent...

Thanks in advance!
Posted

1 solution

You can distinguish the different web clients with the sender parameter passed to your event handler.

But your code looks very bad.
Here some suggestions:

C#
private WebClient StartDownloadFile(Uri source, string targetFilename)
{
  WebClient wc = new WebClient();
  wc.DownloadFileCompleted += DownloadFileCompleted; //without "_"
  wc.DownloadProgressChanged += DownloadProgressChanged;
  wc.DownloadFileAsync(source, targetFilename);
  return wc;
}

private Dictionary<string, WebClient> webClients = new Dictionary<string, WebClient>();

private void DownloadMultipleFiles(string[] sourceFiles)
{
  for (int i = 0; i < sourceFiles.Length - 1; i++)
  {
    webClients[sourceFiles[i]] = StartDownloadFile(
        new Uri(sourceFiles[i]), @"F:\test" + i + ".mp4");
    rtbUrls.AppendText(sourceFiles[z]);
    //Not richTextBox1 -> rtbUrls is a lot better
  }
}

private void DownloadProgressChanged(object sender, EventArgs args) //sth. like this
{
  WebClient wc = (WebClient)sender;
  string url = webClients[wc];
  //Update the corresponding progressbar
}


BTW.:
If you want to display more progress details (e.g. average speed), you should read this article:
Copy a Stream with Progress Reporting[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900