1 using System; 2 using System.Collections.Generic; 3 using System.ComponentModel; 4 using System.Data; 5 using System.Drawing; 6 using System.IO; 7 using System.Linq; 8 using System.Net; 9 using System.Text; 10 using System.Threading.Tasks; 11 using System.Windows.Forms; 12 13 namespace Mesen.GUI.Forms 14 { 15 public partial class frmDownloadProgress : BaseForm 16 { 17 private string _link; 18 private string _filename; 19 private bool _cancel = false; 20 frmDownloadProgress(string link, string filename)21 public frmDownloadProgress(string link, string filename) 22 { 23 InitializeComponent(); 24 25 _link = link; 26 _filename = filename; 27 28 try { 29 File.Delete(_filename); 30 } catch {} 31 32 lblFilename.Text = link; 33 34 tmrStart.Start(); 35 } 36 OnClosing(CancelEventArgs e)37 protected override void OnClosing(CancelEventArgs e) 38 { 39 _cancel = true; 40 base.OnClosing(e); 41 } 42 tmrStart_Tick(object sender, EventArgs e)43 private void tmrStart_Tick(object sender, EventArgs e) 44 { 45 tmrStart.Stop(); 46 47 DialogResult result = System.Windows.Forms.DialogResult.None; 48 49 Task.Run(() => { 50 using(var client = new WebClient()) { 51 client.DownloadProgressChanged += (object s, DownloadProgressChangedEventArgs args) => { 52 this.BeginInvoke((Action)(() => { 53 lblFilename.Text = string.Format("{0} ({1:0.00}Mb)", _link, (double)args.TotalBytesToReceive/1024/1024); 54 progressDownload.Value = args.ProgressPercentage; 55 })); 56 }; 57 client.DownloadFileCompleted += (object s, AsyncCompletedEventArgs args) => { 58 if(!args.Cancelled && args.Error == null && File.Exists(_filename)) { 59 result = System.Windows.Forms.DialogResult.OK; 60 } else if(args.Error != null) { 61 MesenMsgBox.Show("UnableToDownload", MessageBoxButtons.OK, MessageBoxIcon.Error, args.Error.ToString()); 62 result = System.Windows.Forms.DialogResult.Cancel; 63 } 64 }; 65 66 Task downloadTask = null; 67 try { 68 downloadTask = client.DownloadFileTaskAsync(_link, _filename); 69 } catch(Exception ex) { 70 MesenMsgBox.Show("UnableToDownload", MessageBoxButtons.OK, MessageBoxIcon.Error, ex.ToString()); 71 result = System.Windows.Forms.DialogResult.Cancel; 72 } 73 74 if(downloadTask == null) { 75 result = System.Windows.Forms.DialogResult.Cancel; 76 } else { 77 while(!downloadTask.IsCompleted && !_cancel) { 78 System.Threading.Thread.Sleep(200); 79 } 80 81 if(_cancel) { 82 client.CancelAsync(); 83 } else if(result == System.Windows.Forms.DialogResult.None) { 84 result = System.Windows.Forms.DialogResult.OK; 85 } 86 } 87 } 88 89 //Wait a bit for the progress bar to update to 100% (display updates are slower than the .Value updates) 90 System.Threading.Thread.Sleep(500); 91 this.BeginInvoke((Action)(() => { 92 DialogResult = result; 93 this.Close(); 94 })); 95 }); 96 } 97 } 98 } 99