webclient 下载文件但未执行完成

webclient download file but not perform completed

我不想使用 downloadfileAsync 事件我使用了 downloadfile 任何已完成的事件都在那里,仅用于 downloadfile,有任何想法或任何其他方式请提前告诉我谢谢。

  if (!item.IsInstalled && item.IsChecked)
                    {
                        string filename = Path.Combine(Path.GetTempPath(), "AlisAppTemp", "Silverlight");
                        using (StreamWriter sw = new StreamWriter(filename))
                        {
                            sw.WriteLine("Error");
                        }

                        client.DownloadProgressChanged += client_DownloadProgressChanged;
                        client.DownloadFileCompleted += client_DownloadFileCompleted;
                        client.DownloadFile(new Uri("http://download.microsoft.com/download/F/8/C/F8C0EACB-92D0-4722-9B18-965DD2A681E9/30514.00/Silverlight_x64.exe"), filename);
                        item.IsDownloaded = true;
                    }


 private void client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
        {
            double byteIn = double.Parse(e.BytesReceived.ToString());
            double totalBytes = double.Parse(e.TotalBytesToReceive.ToString());
            double percentage = byteIn / totalBytes * 100;
            DownloadData = "Download " + e.BytesReceived / 1024 + " Of " + e.TotalBytesToReceive / 1024;
            this.CurrentProgress = e.ProgressPercentage;
        }

        private void client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
        {
            if (e.UserState != null && e.UserState is AlisApplicationModel)
            {
                AlisApplicationModel ObjApp = e.UserState as AlisApplicationModel;
                ObjApp.IsDownloaded = true;
            }
            if (e.Cancelled)
            {
                this.Cleanup();

            }
            //if (!_bw.IsBusy)
            //{
            //    _bw.RunWorkerAsync();
            //}

        }

DownloadFileCompleted and DownloadProgressChanged 事件将 用于 异步 下载。

您正在使用同步 DownloadFile 方法,因此您的 client_DownloadProgressChangedclient_DownloadFileCompleted 方法将永远不会被调用。

所以你必须使用 DownloadFileAsync 而不是 DownloadFile 方法。