C# 读取网络上下行(不要使用性能计数器的方式)

  • C# 读取网络上下行(不要使用性能计数器的方式)已关闭评论
  • 172 次浏览
  • A+
所属分类:.NET技术
摘要

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)

打开“性能监视器”,点击“性能”,报错

C# 读取网络上下行(不要使用性能计数器的方式)

 使用网上的各种处理都没办法恢复,所以建议使用其它方式获取网络上下行。

下面是使用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;             }         }

 如果再不行可能是网卡出异常了