获取下载和上传速度C#

时间:2010-02-01 21:16:12

标签: c# networking download-speed

我正在寻找一个类或一个库或任何可以让我获得当前下载速度的东西,我已经尝试了很多来自网络的代码,包括FreeMeter但是无法让它工作。

有些人可以提供任何类型的代码来提供这个简单的功能。

非常感谢

2 个答案:

答案 0 :(得分:1)

我猜你想要kb / sec。这是通过取kbreceived并将其除以当前秒减去起始秒来确定的。我不知道如何在C#中使用DateTime,但在VC ++中它会是这样的:

COleDateTimeSpan dlElapsed = COleDateTime::GetCurrentTime()
                           - dlStart;
secs = dlElapsed.GetTotalSeconds();

然后划分:

double kbsec = kbreceived / secs;

要获得kbreceived,您需要进行currentBytes读取,添加已读取的字节数,然后除以1024.

所以,

   // 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;

减去一些特定于实现的功能,无论语言如何,基本概念都是相同的。

答案 1 :(得分:1)

如果您想要当前下载和上传速度,请按以下步骤操作:

制作间隔1秒的计时器,如果您希望以该间隔更新您的选择。 在计时器上打勾,添加以下代码:

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";
    }

我猜这解决了。 如果您有不同的计时器时间间隔,只需划分您给出的时间 我们给出的MAGNITUDE。