C# 读取网络上下行

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%左右,可以不考虑性能问题:

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

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

posted @ 2023-05-23 19:01  log9527  阅读(341)  评论(0编辑  收藏  举报