WebClient DownloadFileAsync - How can I display download speed to the user?
10,563
Solution 1
mWebClient.DownloadProgressChanged += (sender, e) => progressChanged(e.BytesReceived);
//...
DateTime lastUpdate;
long lastBytes = 0;
private void progressChanged(long bytes)
{
if (lastBytes == 0)
{
lastUpdate = DateTime.Now;
lastBytes = bytes;
return;
}
var now = DateTime.Now;
var timeSpan = now - lastUpdate;
var bytesChange = bytes - lastBytes;
var bytesPerSecond = bytesChange / timeSpan.Seconds;
lastBytes = bytes;
lastUpdate = now;
}
And do whatever you need with the bytesPerSecond variable.
Solution 2
We can do this easily by determining how many seconds have passed since the download is started. We can divide BytesReceived value from total seconds to get the speed. Take a look at the following code.
DateTime _startedAt;
WebClient webClient = new WebClient();
webClient.DownloadProgressChanged += OnDownloadProgressChanged;
webClient.DownloadFileAsync(new Uri("Download URL"), "Download Path")
private void OnDownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
if (_startedAt == default(DateTime))
{
_startedAt = DateTime.Now;
}
else
{
var timeSpan = DateTime.Now - _startedAt;
if (timeSpan.TotalSeconds > 0)
{
var bytesPerSecond = e.BytesReceived / (long) timeSpan.TotalSeconds;
}
}
}
Comments
-
Drahcir almost 2 years
That's pretty much the whole question in the title. I have a WPF C# Windows application, I download files for the user and now want to display the speed.