Hy,
I am trying to make a popup indicating the progress of the download of several files. I'm not used to working with await/async and think I'm probably making a big mistake in this case.
The goal is to follow the progress of the file download one by one, I don't want to run all the downloads at the same time. And also have a general look at the progress of all the files to download.
Here is my actual code:
In a first Window I genereate the file list and send it in a PopUp:
Popupdownload inputDialog = new Popupdownload(FileList);
if (inputDialog.ShowDialog() == true)
{
MessageBox.Show(FileList.Count().ToString() + " files are downloaded");
}
My popup class :
public partial class Popupdownload: Window
{
public Popupdownload(List<string> listFiles)
{
InitializeComponent();
DowloadList(listFiles);
}
public async void DowloadList(List<string> listFiles)
{
int counter = 0;
foreach (string e in listFiles)
{
FileInfo TempFile = new FileInfo(System.IO.Path.Combine(App.folderpath, e));
Uri myUri = new Uri("http://********/" + e), UriKind.Absolute);
await DownloadFile(myUri, TempFile.FullName);
counter++;
progressBarTotal.Value = 100*(double)counter / (double)listFiles.Count();
}
}
Stopwatch sw = new Stopwatch();
public async Task DownloadFile(Uri URL, string location)
{
using (WebClient webClient = new WebClient())
{
webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(Completed);
webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChanged);
sw.Start();
try
{
webClient.DownloadFileAsync(URL, location);
}
catch (Exception ex)
{
MessageBox.Show("The file " + location + " hasn't been dowload. Contact admin");
}
}
}
private void ProgressChanged(object sender, System.Net.DownloadProgressChangedEventArgs e)
{
labelSpeed.Content = string.Format("{0} kb/s", (e.BytesReceived / 1024d / sw.Elapsed.TotalSeconds).ToString("0.00"));
progressBar.Value = e.ProgressPercentage;
labelPerc.Content = e.ProgressPercentage.ToString() + "%";
labelDownloaded.Content = string.Format("{0} MB's / {1} MB's",
(e.BytesReceived / 1024d / 1024d).ToString("0.00"),
(e.TotalBytesToReceive / 1024d / 1024d).ToString("0.00"));
}
private void Completed(object sender, AsyncCompletedEventArgs e)
{
sw.Reset();
if (e.Cancelled == true)
{
MessageBox.Show("Download has been canceled.");
}
else
{
// MessageBox.Show("Download completed!");
}
}
}
My current code is a digest of several sources, and I am not sure that some parts work well.
My previous synchronius version of it is working, but hasn't the current file download status preview that I'would like.
It seem to me that all dowloads are launch in same time and it doesn't wait until first has stopped. So it is probably my first issue.
Thanks for your help