Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- private void btnGetDownload_Click(object sender, EventArgs e)
- {
- string fileName = System.IO.Path.GetFileName(videosLinks[0]);
- DownloadFile(videosLinks[0], @"D:\Videos\videos\" + fileName);
- }
- public void DownloadFile(string urlAddress, string location)
- {
- Stopwatch sw = new Stopwatch();
- using (WebClient webClient = new WebClient())
- {
- webClient.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:67.0) Gecko/20100101 Firefox/67.0 Chrome");
- webClient.DownloadFileCompleted += new AsyncCompletedEventHandler((sender, e) => Completed(sender, e, sw));
- webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler((sender, e) => ProgressChanged(sender, e, sw));
- Uri URL = new Uri(urlAddress);
- sw.Start();
- try
- {
- webClient.DownloadFileAsync(URL, location);
- }
- catch (Exception ex)
- {
- MessageBox.Show(ex.Message);
- }
- }
- }
- private void ProgressChanged(object sender, DownloadProgressChangedEventArgs e, Stopwatch sw)
- {
- string downloadProgress = e.ProgressPercentage + "%";
- string downloadSpeed = string.Format("{0} MB/s", (e.BytesReceived / 1024.0 / 1024.0 / sw.Elapsed.TotalSeconds).ToString("0.00"));
- string downloadedMBs = Math.Round(e.BytesReceived / 1024.0 / 1024.0) + " MB";
- string totalMBs = Math.Round(e.TotalBytesToReceive / 1024.0 / 1024.0) + " MB";
- // Format progress string
- string progress = $"{downloadedMBs}/{totalMBs} ({downloadProgress}) @ {downloadSpeed}"; // 10 MB / 100 MB (10%) @ 1.23 MB/s
- progressBarText1.Value = e.ProgressPercentage;
- progressBarText1.Refresh();
- progressBarText1.CustomText = progress;
- }
- private void Completed(object sender, AsyncCompletedEventArgs e, Stopwatch sw)
- {
- if (e.Cancelled == true)
- {
- btnGetDownload.Text = "Fails.";
- sw.Stop();
- }
- else
- {
- btnGetDownload.Text = "Finish.";
- sw.Stop();
- if (videosLinks.Count > 0)
- {
- videosLinks.RemoveAt(0);
- string fileName = System.IO.Path.GetFileName(videosLinks[0]);
- DownloadFile(videosLinks[0], @"D:\Videos\videos\" + fileName);
- }
- }
- }
- static readonly string[] SizeSuffixes =
- { "bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB" };
- static string SizeSuffix(Int64 value, Int64 totalValue)
- {
- if (value < 0) { return "-" + SizeSuffix(-value, totalValue); }
- int i = 0;
- decimal dValue = (decimal)value;
- while (Math.Round(dValue / 1024) >= 1)
- {
- dValue /= 1024;
- i++;
- }
- return string.Format("{0:n1} {1} {2}", dValue, SizeSuffixes[i], (totalValue / 1024d / 1024d).ToString("0.00"));
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement