C# 讀取網路上下行有多種方式,其中有一種是使用System.Net.NetworkInformation命名空間中的NetworkInterface類和PerformanceCounter類,該方式其實讀的是windows系統的性能計數器中的Network Interface類別的數據。 方式如下 ...
C# 讀取網路上下行有多種方式,其中有一種是使用System.Net.NetworkInformation
命名空間中的NetworkInterface
類和PerformanceCounter
類,該方式其實讀的是windows系統的性能計數器中的Network Interface類別的數據。
方式如下:
NetworkInterface networkInterface = NetworkInterface.GetAllNetworkInterfaces() .FirstOrDefault(i => i.Name.Equals(interfaceName, StringComparison.OrdinalIgnoreCase)); if (networkInterface == null) { Console.WriteLine("Network interface not found."); return; } PerformanceCounter downloadCounter = new PerformanceCounter("Network Interface", "Bytes Received/sec", networkInterface.Description); PerformanceCounter uploadCounter = new PerformanceCounter("Network Interface", "Bytes Sent/sec", networkInterface.Description); while (true) { float downloadSpeed = downloadCounter.NextValue(); float uploadSpeed = uploadCounter.NextValue(); Console.WriteLine($"Download Speed: {downloadSpeed} bytes/sec"); Console.WriteLine($"Upload Speed: {uploadSpeed} bytes/sec"); Thread.Sleep(1000); // 每秒更新一次網速 }
但是使用性能計數器有時候會拋異常:
異常: System.InvalidOperationException: 類別不存在。
在 System.Diagnostics.PerformanceCounterLib.CounterExists(String machine, String category, String counter)
在 System.Diagnostics.PerformanceCounter.InitializeImpl()
在 System.Diagnostics.PerformanceCounter..ctor(String categoryName, String counterName, String instanceName, Boolean readOnly)
在 System.Diagnostics.PerformanceCounter..ctor(String categoryName, String counterName, String instanceName)
打開“性能監視器”,點擊“性能”,報錯
使用網上的各種處理都沒辦法恢復,所以建議使用其它方式獲取網路上下行。
下麵是使用WMI (Windows Management Instrumentation)的方式(需要使用管理員身份運行):
string interfaceName = "Ethernet"; // 指定網路介面的名稱 ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_PerfFormattedData_Tcpip_NetworkInterface"); ManagementObjectCollection objects = searcher.Get(); foreach (ManagementObject obj in objects) { string name = obj["Name"].ToString(); if (name.Equals(interfaceName, StringComparison.OrdinalIgnoreCase)) { ulong bytesReceived = Convert.ToUInt64(obj["BytesReceivedPerSec"]); ulong bytesSent = Convert.ToUInt64(obj["BytesSentPerSec"]); Console.WriteLine($"Download Speed: {bytesReceived} bytes/sec"); Console.WriteLine($"Upload Speed: {bytesSent} bytes/sec"); break; } }
如果再不行可能是網卡出異常了