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

发布时间 2023-05-23 19:06:30作者: log9527

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;
            }
        }