Get Download and Upload Speeds C#
-
24-09-2019 - |
Question
I'm looking for a class or a library or anything that will allow me to get the current download speed, I've tried a lot of code from the net including FreeMeter but can't get it to work.
Can some provide any sort of code just to give this simple functionality.
Thanks a lot
Solution
I'm guessing you want kb/sec. That is determined by taking kbreceived
and dividing it by the current seconds minus the starting seconds. I'm not sure how to do the DateTime for this in C#, but in VC++ it would be like so:
COleDateTimeSpan dlElapsed = COleDateTime::GetCurrentTime()
- dlStart;
secs = dlElapsed.GetTotalSeconds();
You then divide:
double kbsec = kbreceived / secs;
To get kbreceived
, you need to take the currentBytes
read, add in bytes already read, then divide by 1024.
So,
// chunk size 512.. could be higher up to you
while (int bytesread = file->Read(charBuf, 512))
{
currentbytes = currentbytes + bytesread;
// Set progress position by setting pos to currentbytes
}
int percent = currentbytes * 100 / x ( our file size integer
from above);
int kbreceived = currentbytes / 1024;
Minus some implementation specific functions, the basic concept is the same regardless of language.
OTHER TIPS
If you want Current Download and Upload Speed, here is how :
Make a timer of interval 1 second, if you want it to update at that interval, your choice. On the timers tick, add this code :
using System.Net.NetworkInformation;
int previousbytessend = 0;
int previousbytesreceived = 0;
int downloadspeed;
int uploadspeed;
IPv4InterfaceStatistics interfaceStats;
private void timer1_Tick(object sender, EventArgs e)
{
//Must Initialize it each second to update values;
interfaceStats = NetworkInterface.GetAllNetworkInterfaces()[0].GetIPv4Statistics();
//SPEED = MAGNITUDE / TIME ; HERE, TIME = 1 second Hence :
uploadspeed = (interfaceStats.BytesSent - previousbytessend) / 1024; //In KB/s
downloadspeed = (interfaceStats.BytesReceived - previousbytesreceived) / 1024;
previousbytessend= NetworkInterface.GetAllNetworkInterfaces()[0].GetIPv4Statistics().BytesSent;
previousbytesreceived= NetworkInterface.GetAllNetworkInterfaces()[0].GetIPv4Statistics().BytesReceived;
downloadspeedlabel.Text = Math.Round(downloadspeed, 2) + " KB/s"; //Rounding to 2 decimal places
uploadspeedlabel.Text = Math.Round(uploadspeed, 2) + "KB/s";
}
I guess that solves it. If you have different time interval for the timer, just divide the time you gave with the MAGNITUDE we have given.