Downloading files with C#
When I am running my method to download a file, it is not waiting for the download to finish before calling the next method "unzipfiles", how could I make it wait until the file is downloaded?
private void Download_Click(object sender, EventArgs e)
{
WebClient webClient = new WebClient();
webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(Completed);
webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChanged);
webClient.DownloadFileAsyn开发者_运维知识库c(new Uri("http://download1us.softpedia.com/dl/f4932a906a7dd98c7ff002b07e9bd94b/4e065004/100079174/software/portable/security/ccsetup307.zip"), @"ccsetup307.zip");
// Call unzip method
unzipfiles();
}
Call your unzipfiles()
method in DownloadFileCompleted event
You're doing the download asynchronously, which means that the code just starts the download, which is then done in the background. Once the download is completed, the DownloadFileCompleted
event is fired and your Completed
method is called.
You should move the call to unzipfiles
to the Completed
method.
You could just use DownloadFile()
instead of DownloadFileAsync()
. However that would mean the UI would be locked up during the download of the files, and you should try to avoid that.
Better solution would be to call unzipfiles()
from your Completed()
method.
You should unzip in your Completed
method:
void Completed(object sender, AsyncCompletedEventArgs e)
{
unzipfiles();
}
or run download synchronously:
WebClient webClient = new WebClient();
webClient.DownloadFile(new Uri("http://download1us.softpedia.com/dl/f4932a906a7dd98c7ff002b07e9bd94b/4e065004/100079174/software/portable/security/ccsetup307.zip"), @"ccsetup307.zip");
unzipfiles();
What you're doing is calling the async implementation of Download File.
For simplicity you can use-
webClient.DownloadFile(new Uri("http://download1us.softpedia.com/dl/f4932a906a7dd98c7ff002b07e9bd94b/4e065004/100079174/software/portable/security/ccsetup307.zip"), @"ccsetup307.zip");
Without the events registring.
If you want to use the async implementation, this means that when the file is downloaded the WebClient object will call the - Completed method - where you can do the Unzip ....
精彩评论