using System.Diagnostics;
using System.IO;
using System.Net;
WebClient webClient; // Our WebClient that will be doing the downloading for us
Stopwatch sw = new Stopwatch(); // The stopwatch which we will be using to calculate the download speed
public void downloadFile(string urlAddress, string location)
{
using (webClient = new WebClient())
{
webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(Completed);
webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChanged);
try
{
// The variable that will be holding the url address
Uri URL;
// Make sure the url starts with "http://"
if (!urlAddress.StartsWith("http://", StringComparison.OrdinalIgnoreCase))
URL = new Uri("http://" + urlAddress);
else
URL = new Uri(urlAddress);
// Start the stopwatch which we will be using to calculate the download speed
sw.Start();
// Start downloading the file
webClient.DownloadFileAsync(URL, location);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
// The event that will fire whenever the progress of the WebClient is changed
private void ProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
try
{
// Calculate download speed and output it to label3
if (labelPerc.Text != (Convert.ToDouble(e.BytesReceived) / 1024 / sw.Elapsed.TotalSeconds).ToString("0"))
labelSpeed.Text = (Convert.ToDouble(e.BytesReceived) / 1024 / sw.Elapsed.TotalSeconds).ToString("0.00") + " kb/s";
// Update the progressbar percentage only when the value is not the same (to avoid updating the control constantly)
if (progressBar.Value != e.ProgressPercentage)
progressBar.Value = e.ProgressPercentage;
// Show the percentage on our label (update only if the value isn't the same to avoid updating the control constantly)
if (labelPerc.Text != e.ProgressPercentage.ToString() + "%")
labelPerc.Text = e.ProgressPercentage.ToString() + "%";
// Update the label with how much data have been downloaded so far and the total size of the file we are currently downloading
labelDownloaded.Text = (Convert.ToDouble(e.BytesReceived) / 1024 / 1024).ToString("0.00") + " Mb's" + " / " + (Convert.ToDouble(e.TotalBytesToReceive) / 1024 / 1024).ToString("0.00") + " Mb's";
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
// The event that will trigger when the WebClient is completed
private void Completed(object sender, AsyncCompletedEventArgs e)
{
sw.Reset();
if (e.Cancelled == true)
{
File.Delete(saveFileDialog.FileName); // Delete the incomplete file if the download is canceled
MessageBox.Show("Canceled");
}
else
MessageBox.Show("Download completed!");
}
Взято с www.fluxbytes.comИсходники по языку программирования CSharp
Если вы столкнулись с проблемой и хотите поделиться своим опытом, знаниями или у вас есть интересная статья с иностранного сайта, предложение новой темы, статью которую Вы хотите видеть в ближайшем будущем, расскажите нам об этом и мы обязательно поделимся этими знаниями со всеми. Возможно, для других ваши знания, опыт и советы окажутся очень ценными и помогут вовремя найти правильный выход или не совершить ошибок.Так же если у вас есть предложение о сотрудничестве, пожелания, указать на нарушения сайта или просто сказать слова благодарности, все это вы можете сделать через форму обратной связи. Читать дальше
Скачивание файла с интернета (progressbar and download speed)
Также читайте: Network
Copyright © 2011-2015 Справочник по C#. Все права защищены.


Комментариев нет:
Отправить комментарий
Большая просьба, не писать в комментариях всякую ерунду не по теме!