简体   繁体   中英

Wait for DownloadFileAsync to finish downloading and then do something

So basically my DownloadFile is:

public void DownloadFile()
{
    settings_btn.Enabled = false;
    label1.Text = "Checking for updates...";
    //Defines the server's update directory
    string Server = "http://downloadurl/update/";

    //Defines application root
    string Root = AppDomain.CurrentDomain.BaseDirectory;

    //Make sure version file exists
    FileStream fs = null;
    if (!File.Exists("pversion"))
    {
        using (fs = File.Create("pversion")){}
        using (StreamWriter sw = new StreamWriter("pversion")){sw.Write("1.0");}
    }
    //checks client version
    string lclVersion;
    using (StreamReader reader = new StreamReader("pversion"))
    {
        lclVersion = reader.ReadLine();
    }
    decimal localVersion = decimal.Parse(lclVersion);

    //server's list of updates
    XDocument serverXml = XDocument.Load(@Server + "pUpdates.xml");

    //The Update Process
    foreach (XElement update in serverXml.Descendants("pupdate"))
    {
        string version = update.Element("pversion").Value;
        string file = update.Element("pfile").Value;

        decimal serverVersion = decimal.Parse(version);


        string sUrlToReadFileFrom = Server + file;

        string sFilePathToWriteFileTo = Root + file;

        if (serverVersion > localVersion)
        {
            using (webClient = new WebClient())
            {
                webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(Completed);
                webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChanged);

                // The variable that will be holding the url address (making sure it starts with http://)
                Uri url = new Uri(sUrlToReadFileFrom);

                // Start the stopwatch which we will be using to calculate the download speed
                sw.Start();

                try
                {
                    // Start downloading the file
                    webClient.DownloadFileAsync(url, sFilePathToWriteFileTo);

                    // Change the currently running executable so it can be overwritten.
                    Process thisprocess = Process.GetCurrentProcess();
                    string me = thisprocess.MainModule.FileName;
                    string bak = me + ".bak";
                    if (File.Exists(bak))
                    {
                        File.Delete(bak);
                    }
                    File.Move(me, bak);
                    File.Copy(bak, me);

                    //unzip
                    using (ZipFile zip = ZipFile.Read(file))
                    {
                        foreach (ZipEntry zipFiles in zip)
                        {
                            zipFiles.Extract(Root + "\\", true);
                        }
                    }

                    //download new version file
                    webClient.DownloadFile(Server + "pversion.txt", @Root + "pversion");

                    //Delete Zip File
                    deleteFile(file);

                    var spawn = Process.Start(me);
                    thisprocess.CloseMainWindow();
                    thisprocess.Close();
                    thisprocess.Dispose();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
        }
    }
}

And my problem is that once it finds a new version and starts downloading the file webClient.DownloadFileAsync(url, sFilePathToWriteFileTo); , it instantly runs the code below which is the changing name, unzipping and downloading new version file progress

What I want it to do is wait for it to finish downloading the file, and THEN do the rest. How do I do this?

-- In case this is necessary, ProgressChanged:

private void ProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
    label3.Text = string.Format("{0} kb/s", (e.BytesReceived / 1024d / sw.Elapsed.TotalSeconds).ToString("0.00")) + " " + string.Format("{0} MB's / {1} MB's", (e.BytesReceived / 1024d / 1024d).ToString("0.00"), (e.TotalBytesToReceive / 1024d / 1024d).ToString("0.00"));;
    progressBar1.Value = e.ProgressPercentage;
    label1.Text = e.ProgressPercentage.ToString() + "%";
}

and Completed:

private void Completed(object sender, AsyncCompletedEventArgs e)
{
    sw.Reset();
    if (e.Cancelled == true)
    {
        label1.Text = "Download cancelled!";
    }
    else
    {
        label1.Text = "Download completed!";
    }
}

You can use the DownloadFile method. The Async word means that this method will run asynchronous (in other thread), that's why it's goes to next line praticaly instantly. If you want wait for download ends, use the DownloadFile instead of DownloadFileAsync

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM