显示网速

private List<NetworkInterface> netList;//存储网卡列表
        private long receivedBytes;//记录上一次总接收字节数
        private long sentBytes;//记录上一次总发送字节数
        /// <summary>
        /// 显示当前网络下载和上传速度
        /// </summary>
        private void ShowSpeed()
        {
            long totalReceivedbytes = 0;//记录本次总接收字节数
            long totalSentbytes = 0;//记录本次总发送字节数
            foreach (NetworkInterface net in netList)//遍历网卡列表
            {
                IPv4InterfaceStatistics interfaceStats = net.GetIPv4Statistics(); //获取IPv4统计信息
                totalReceivedbytes += interfaceStats.BytesReceived;//获取接收字节数,并累计
                totalSentbytes += interfaceStats.BytesSent;//获取发送字节数,并累计
            }
            long recivedSpeed = totalReceivedbytes - receivedBytes;//计算本次接收字节数(本次-上次)
            long sentSpeed = totalSentbytes - sentBytes;//计算本次发送字节数(本次-上次)
            //如果上一次接收和发送值为0,将下载和上传速度设置为0
            if (receivedBytes == 0 && sentBytes == 0)
            {
                recivedSpeed = 0;
                sentSpeed = 0;
            }
            label1.Text = "[" + recivedSpeed / 1024 + " KB/s]"; //显示下载速度
            label2.Text = "[" + sentSpeed / 1024 + " KB/s]";//显示上传速度
            receivedBytes = totalReceivedbytes;//记录上一次总接收字节数
            sentBytes = totalSentbytes;//记录上一次总发送字节数
        }

猜你喜欢

转载自blog.csdn.net/qq_35439171/article/details/82951289