獲取網絡傳輸速度
使用PerformanceCounter類(System.Diagnostics)
1、源碼:
class NETSpeed
{
//網絡發送速度
public float NetTrafficSend { get; set; }
//網絡接收速度
public float NetTrafficReceive { get; set; }
private PerformanceCounterCategory performanceNetCounterCategory;
private PerformanceCounter[] trafficSentCounters;
private PerformanceCounter[] trafficReceivedCounters;
//用於記錄性能對象實例名稱
private string[] interfaces = null;
public void InitNetCounters()
{
performanceNetCounterCategory = new PerformanceCounterCategory("Network Interface");
//獲取性能對象實例名稱
interfaces = performanceNetCounterCategory.GetInstanceNames();
int length = interfaces.Length;
if (length > 0)
{
trafficSentCounters = new PerformanceCounter[length];
trafficReceivedCounters = new PerformanceCounter[length];
}
for (int i = 0; i < length; i++)
{
trafficReceivedCounters[i] = new PerformanceCounter("Network Interface", "Bytes Received/sec", interfaces[i]);
trafficSentCounters[i] = new PerformanceCounter("Network Interface", "Bytes Sent/sec", interfaces[i]);
}
}
/// <summary>
/// 網絡上傳速度
/// </summary>
public void GetCurretTrafficSent()
{
int length = interfaces.Length;
float sendSum = 0.0F;
for (int i = 0; i < length; i++)
{
//獲取上傳數據量
float temp = trafficSentCounters[i].NextValue();
//第一次獲取值爲0的處理方法
if (i== 0 && temp ==0)
{
Thread.Sleep(500);
temp = trafficSentCounters[i].NextValue();
}
sendSum += temp;
}
float tmp = (sendSum / 1024);
NetTrafficSend = (float)(Math.Round((double)tmp, 1));
}
/// <summary>
/// 網絡下載速度
/// </summary>
public void GetCurrentTrafficReceived()
{
int length = interfaces.Length;
float receiveSum = 0.0F;
for (int i = 0; i < length; i++)
{
//獲取下載數據量
float temp = trafficReceivedCounters[i].NextValue();
if (i== 0 && temp ==0)
{
Thread.Sleep(500);
temp = trafficReceivedCounters[i].NextValue();
}
receiveSum += temp;
}
float tmp = (receiveSum / 1024);
NetTrafficReceive = (float)(Math.Round((double)tmp, 1));
}
}
使用方法:將上述內容保存爲.cs類
調用方法:
//實例化對象
NETSpeed netSpeed = new NETSpeed();
//初始化
netSpeed.InitNetCounters();
//獲取上傳速度
netSpeed.GetCurretTrafficSent();
float netTrafficSent = netSpeed.NetTrafficSend;
Console.WriteLine("網絡上傳速度:" + netTrafficSent + "KB/s");
//獲取下載速度
netSpeed.GetCurrentTrafficReceived();
float netTrafficReceive = netSpeed.NetTrafficReceive;
Console.WriteLine("網絡下載速度:" + netTrafficReceive + "KB/s");
以上方法獲取的爲一秒內的網速
2、運行結果:
對比任務管理器:(數據不是相同時刻,此處只爲對比)
3、注意事項:
1、注意單位的不同,代碼處獲取的單位爲KB/S 任務管理器的爲Kb/s 兩者相差8倍
2、文章來源與實踐,存在問題請留言!
3、轉載請標註來源,謝謝您的閱讀!