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)
打开“性能监视器”,点击“性能”,报错
使用@TanZhiWei 的方式可以解决:https://www.cnblogs.com/terryK/p/17491818.html
下面是使用WMI (Windows Management Instrumentation)的方式,该方式cpu保持在0~1%左右,可以不考虑性能问题:文章来源:https://www.toymoban.com/news/detail-456381.html
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; } }
如果再不行可能是网卡出异常了文章来源地址https://www.toymoban.com/news/detail-456381.html
到了这里,关于C# 读取网络上下行(不要使用性能计数器的方式)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!