I am making this application where I have to download multiple files from my website according to whether a checkbox is checked or not. I am using DownloadFileAsync method for downloading the files.
The problem I have is that, once the download starts for the first file. It continues on with rest of the code. For example. It will add "1" to the listbox before the download even finishes and then also move on to next if statement and execute the download for it as well and add "2" to listbox as soon as the download starts. Below is the code I am using.
private void button1_Click(object sender, EventArgs e)
{
if (checkBox1.Checked)
{
WebClient client = new WebClient();
client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged);
client.DownloadFileCompleted += new AsyncCompletedEventHandler(client_DownloadFileCompleted);
client.DownloadFileAsync(new Uri("https://speed.hetzner.de/100MB.bin"), "100mb");
listBox1.Items.Add("1");
}
if (checkBox2.Checked)
{
WebClient client = new WebClient();
client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged);
client.DownloadFileCompleted += new AsyncCompletedEventHandler(client_DownloadFileCompleted);
client.DownloadFileAsync(new Uri("https://speed.hetzner.de/100MB.bin"), "200mb");
listBox1.Items.Add("2");
}
}
void client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
double bytesIn = double.Parse(e.BytesReceived.ToString());
double totalBytes = double.Parse(e.TotalBytesToReceive.ToString());
double percentage = bytesIn / totalBytes * 100;
progressBar1.Value = int.Parse(Math.Truncate(percentage).ToString());
}
void client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
{
progressBar1.Value = 0;
}
I tried using async and wait but I couldn't get it to work. In short, how can I make the code download the first file completely, then add "1" to the listbox and only then move to the second if statement to download second file.
Thanks in advance.