完成异步下载两次而不是一次

时间:2015-09-05 11:22:55

标签: c# wpf

我的应用程序中有这个代码,允许用户下载最新版本的应用程序。应用程序下载完成后,如果用户想要打开文件位置以查看文件,则会打开提示。

但是,该工具会启动两个消息框,而不是仅启动一次。我不确定我是否遗漏了什么。

private void BTN_GNV_MouseUp(object sender, MouseButtonEventArgs e)
{
    string URLDir = "http://shard.combatkingz.com/downloads/";
    string URLName = "DayZ Config Tweak tool v" + Properties.Settings.Default.AvailableVersion + ".exe";
    string URLFull = "";
    using (WebClient DLWC = new WebClient())
    {
        URLFull = URLDir + URLName;
        GlobalVars.DLPath = System.Environment.CurrentDirectory + "\\" + URLName;
        try
        {
            DLWC.DownloadFileAsync(new Uri(URLFull), GlobalVars.DLPath);
            DLWC.DownloadProgressChanged += DLWC_DownloadProgressChanged;
        }
        catch
        {
            MessageBox.Show("There was an error downloading the file.", GlobalVars.APPNAME, MessageBoxButton.OK, MessageBoxImage.Error);
#if DEBUG
#else
            AddDownloadToDB("Failed");
#endif
        }
    }
}
void DLWC_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
    PB_GNV.Width = (BTN_GNV.Width / 100) * e.ProgressPercentage;
    if (PB_GNV.Width == BTN_GNV.Width && e.TotalBytesToReceive == e.BytesReceived)
    {
        MessageBoxResult nav = MessageBox.Show("New version downloaded. Do you want to navigate to the folder?", GlobalVars.APPNAME, MessageBoxButton.YesNo, MessageBoxImage.Error);
        if (nav == MessageBoxResult.Yes)
        {
            string argument = @"/select, " + @GlobalVars.DLPath;
            System.Diagnostics.Process.Start("explorer.exe", argument);
#if DEBUG
#else
            AddDownloadToDB("Success");
#endif
        }
    }
}

1 个答案:

答案 0 :(得分:3)

我怀疑DownloadProgressChanged事件在接收到最后一个字节并且文件已完成时触发。使用DownloadFileCompleted事件可以解决问题。