2010-02-01 84 views
4

我正在寻找一个类或图书馆或任何可以让我获得当前下载速度的东西,我已经尝试了很多包括FreeMeter在内的网络代码,但无法获得它工作。获取下载和上传速度C#

有些人可以提供任何类型的代码,只是为了给这个简单的功能。

非常感谢

+0

你想达到什么目的?测量整个管道的速度,还是试图获得正在执行的下载的速度? – 2010-02-01 21:20:07

+0

@Roboto,现在我可以 – 2010-02-02 13:58:08

+0

我基本上试图获得网络在系统上的使用情况,如果它是空闲的或者是否有任何下载正在进行等。 – 2010-02-03 23:15:34

回答

1

我猜你想kb /秒。这取决于kbreceived并将其除以当前秒数减去开始秒数。我不知道怎么办的DateTime这在C#中,但在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秒的计时器,如果你希望它在该时间间隔更新,你的选择。 在计时器滴答,添加以下代码:

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。

相关问题