2010-02-01 180 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。