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)的方式(需要使用管理员身份运行):

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

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值