using System; using System.IO; using System.Net; using System.Diagnostics; using System.Windows.Forms; using System.ComponentModel; namespace Custom_Installer { class Download { private Stopwatch DownloadTimer; public String SavePath { get; set; } public Uri Address { get; set; } public ProgressBar Progress { get; set; } public Label Information { get; set; } public Boolean IsFinished; public void StartDownload() { try { WebClient DownloadClient = new WebClient(); DownloadClient.DownloadFileCompleted += DownloadClient_DownloadFileCompleted; DownloadClient.DownloadProgressChanged += DownloadClient_DownloadProgressChanged; DownloadTimer = new Stopwatch(); DownloadTimer.Start(); DownloadClient.DownloadFileAsync(Address, SavePath); } catch (Exception Error) { File.Delete(String.Format("{0}{1}", String.Format(Properties.Settings.Default.Save_Location, Properties.Settings.Default.Server_Name), Properties.Settings.Default.Extract_Name)); Program.Message(Error.Message); Program.Shutdown(); } } private void DownloadClient_DownloadProgressChanged(Object Sender, DownloadProgressChangedEventArgs Args) { Int64 Completed = Args.BytesReceived; Int64 FileSize = Args.TotalBytesToReceive; Int32 ProgressPercentage = Args.ProgressPercentage; String Speed = String.Format("{0} KB/s", (Completed / 1024d / DownloadTimer.Elapsed.TotalSeconds).ToString("0.00")); if (Progress != null) { Progress.BeginInvoke((Action)(() => { Progress.Value = ProgressPercentage; })); } if (Information != null) { Information.BeginInvoke((Action)(() => { Information.Text = String.Format("Downloading: {0}% [{1}/{2}] {3}", ProgressPercentage, ConvertBytes(Completed), ConvertBytes(FileSize), Speed); })); } } private void DownloadClient_DownloadFileCompleted(Object Sender, AsyncCompletedEventArgs Args) { if (Progress != null) { Progress.BeginInvoke((Action)(() => { Progress.Value = 100; })); } if (Information != null) { Information.BeginInvoke((Action)(() => { Information.Text = "Downloaded Successfully"; })); } IsFinished = true; } static String ConvertBytes(Int64 Amount) { String[] Suffix = { "B", "KB", "MB", "GB", "TB", "PB", "EB" }; Int64 Bytes = Math.Abs(Amount); Int32 Place = Convert.ToInt32(Math.Floor(Math.Log(Bytes, 1024))); Double Number = Math.Round(Bytes / Math.Pow(1024, Place), 1); return String.Format("{0} {1}", Convert.ToString(Math.Sign(Amount) * Number), Suffix[Place]); } } }