C# 获取windows的上传下载速度

2024-06-05 08:04

本文主要是介绍C# 获取windows的上传下载速度,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

直接利用CZGL.SystemInfo代码
UnitType.cs


/// <summary>
/// 单位
/// </summary>
public enum UnitType : int
{/// <summary>/// Byte/// </summary>/// B = 0,/// <summary>/// KB/// </summary>KB,/// <summary>/// MB/// </summary>MB,/// <summary>/// GB/// </summary>GB,/// <summary>/// TB/// </summary>TB,/// <summary>/// PB/// </summary>PB
}

SizeInfo.cs


/// <summary>
/// 大小信息
/// </summary>
public struct SizeInfo
{/// <summary>/// Byte 长度/// </summary>public long ByteLength { get; private set; }/// <summary>/// 大小/// </summary>public decimal Size { get; set; }/// <summary>/// 单位/// </summary>public UnitType SizeType { get; set; }/// <summary>/// 将字节单位转换为合适的单位/// </summary>/// <param name="byteLength">字节长度</param>/// <returns></returns>public static SizeInfo Get(long byteLength){UnitType unit = 0;decimal number = byteLength;if (byteLength < 1000){return new SizeInfo(){ByteLength = byteLength,Size = byteLength,SizeType = UnitType.B};}// 避免出现 1023B 这种情况;这样 1023B 会显示 0.99KBwhile (Math.Round(number / 1000) >= 1){number = number / 1024;unit++;}return new SizeInfo{Size = Math.Round(number, 2),SizeType = unit,ByteLength = byteLength};throw new Exception();}
}

Rate.cs

/// <summary>
/// 网速
/// </summary>
public struct Rate
{public Rate(DateTime startTime, long receivedLength, long sendLength){StartTime = startTime;ReceivedLength = receivedLength;SendLength = sendLength;}/// <summary>/// 记录时间/// </summary>public DateTime StartTime { get; private set; }/// <summary>/// 此网卡总接收网络流量字节数/// </summary>public long ReceivedLength { get; private set; }/// <summary>/// 此网卡总发送网络流量字节数/// </summary>public long SendLength { get; private set; }
}

NetworkInfo.cs

using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Runtime.InteropServices;/// <summary>/// 网络接口信息/// </summary>public class NetworkInfo{private NetworkInterface _instance;private NetworkInfo(NetworkInterface network){_instance = network;}/// <summary>/// 当前实例使用的网络接口/// </summary>public NetworkInterface NetworkInterface => _instance;#region 基础信息/// <summary>/// 获取网络适配器的标识符/// </summary>/// <remarks>ex:{92D3E528-5363-43C7-82E8-D143DC6617ED}</remarks>public string Id => _instance.Id;/// <summary>/// 网络的 Mac 地址/// </summary>/// <remarks>ex: 1C997AF108E3</remarks>public string Mac => _instance.GetPhysicalAddress().ToString();/// <summary>/// 网卡名称/// </summary>/// <remarks>ex:以太网,WLAN</remarks>public string Name => _instance.Name;/// <summary>/// 描述网络接口的用户可读文本,/// 在 Windows 上,它通常描述接口供应商、类型 (例如,以太网) 、品牌和型号;/// </summary>/// <remarks>ex:Realtek PCIe GbE Family Controller、  Realtek 8822CE Wireless LAN 802.11ac PCI-E NIC</remarks>public string Trademark => _instance.Description;/// <summary>/// 获取网络连接的当前操作状态<br />/// </summary>public OperationalStatus Status => _instance.OperationalStatus;/// <summary>/// 获取网卡接口类型<br />/// </summary>public NetworkInterfaceType NetworkType => _instance.NetworkInterfaceType;/// <summary>/// 网卡链接速度,每字节/秒为单位/// </summary>/// <remarks>如果是-1,则说明无法获取此网卡的链接速度;例如 270_000_000 表示是 270MB 的链接速度</remarks>public long Speed => _instance.Speed;/// <summary>/// 是否支持 Ipv4/// </summary>public bool IsSupportIpv4 => _instance.Supports(NetworkInterfaceComponent.IPv4);/// <summary>/// 获取分配给此接口的任意广播 IP 地址。只支持 Windows/// </summary>/// <remarks>一般情况下为空数组</remarks>public IPAddress[] AnycastAddresses{get{if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)){return _instance.GetIPProperties().AnycastAddresses.Select(x => x.Address).ToArray();}else{return Array.Empty<IPAddress>();}}}/// <summary>/// 获取分配给此接口的多播地址,ipv4、ipv6/// </summary>/// <remarks>ex:ff01::1%9 ff02::1%9<br />/// ff02::fb%9<br />/// ff02::1:3%9<br />/// ff02::1:ff61:9ae7%9<br />/// 224.0.0.1</remarks>public IPAddress[] MulticastAddresses => _instance.GetIPProperties().MulticastAddresses.Select(x => x.Address).ToArray();/// <summary>/// 获取分配给此接口的单播地址,ipv4、ipv6/// </summary>/// <remarks>ex:192.168.3.38</remarks>public IPAddress[] UnicastAddresses => _instance.GetIPProperties().UnicastAddresses.Select(x => x.Address).ToArray();/// <summary>/// 获取此接口的 IPv4 网关地址,ipv4、ipv6/// </summary>/// <remarks>ex:fe80::1677:40ff:fef9:bf95%5、192.168.3.1</remarks>public IPAddress[] GatewayAddresses => _instance.GetIPProperties().GatewayAddresses.Select(x => x.Address).ToArray();/// <summary>/// 获取此接口的域名系统 (DNS) 服务器的地址,ipv4、ipv6/// </summary>/// <remarks>ex:fe80::1677:40ff:fef9:bf95%5、192.168.3.1</remarks>public IPAddress[] DnsAddresses => _instance.GetIPProperties().DnsAddresses.ToArray();/// <summary>/// 是否支持 Ipv6/// </summary>public bool IsSupportIpv6 => _instance.Supports(NetworkInterfaceComponent.IPv6);#endregion/// <summary>/// 当前主机是否能够与其他计算机通讯(公网或内网),如果任何网络接口标记为 "up" 且不是环回或隧道接口,则认为网络连接可用。/// </summary>public static bool GetIsNetworkAvailable => NetworkInterface.GetIsNetworkAvailable();/// <summary>/// 计算 IPV4 的网络流量/// </summary>/// <returns></returns>/// <exception cref="NotSupportedException">当前网卡不支持 IPV4</exception>public Rate GetIpv4Speed(){// 当前网卡不支持 IPV4if (!IsSupportIpv4) return default;var ipv4Statistics = _instance.GetIPv4Statistics();var speed = new Rate(DateTime.Now, ipv4Statistics.BytesReceived, ipv4Statistics.BytesSent);return speed;}/// <summary>/// 计算 IPV4 、IPV6 的网络流量/// </summary>/// <returns></returns>public Rate IpvSpeed(){var ipvStatistics = _instance.GetIPStatistics();var speed = new Rate(DateTime.Now, ipvStatistics.BytesReceived, ipvStatistics.BytesSent);return speed;}/// <summary>/// 获取所有 IP 地址/// </summary>/// <returns></returns>public static IPAddress[] GetIPAddresses(){var hostName = Dns.GetHostName();return Dns.GetHostAddresses(hostName);}/// <summary>/// 获取当前真实 IP/// </summary>/// <returns></returns>public static IPAddress? TryGetRealIpv4(){var addrs = GetIPAddresses();var ipv4 = addrs.FirstOrDefault(x => x.AddressFamily == AddressFamily.InterNetwork);return ipv4;}/// <summary>/// 获取真实网卡/// </summary>/// <returns></returns>public static NetworkInfo? TryGetRealNetworkInfo(){var realIp = TryGetRealIpv4();if (realIp == null){return default;}var infos = NetworkInfo.GetNetworkInfos().ToArray();var info = infos.FirstOrDefault(x => x.UnicastAddresses.Any(x => x.MapToIPv4().ToString() == realIp.MapToIPv4().ToString()));if (info == null){return default;}return info;}/// <summary>/// 获取此主机中所有网卡接口/// </summary>/// <returns></returns>public static NetworkInfo[] GetNetworkInfos(){return NetworkInterface.GetAllNetworkInterfaces().Select(x => new NetworkInfo(x)).ToArray();}/// <summary>/// 计算网络流量速率/// </summary>/// <param name="oldRate"></param>/// <param name="newRate"></param>/// <returns></returns>public static (SizeInfo Received, SizeInfo Sent) GetSpeed(Rate oldRate, Rate newRate){var receive = newRate.ReceivedLength - oldRate.ReceivedLength;var send = newRate.SendLength - oldRate.SendLength;var interval = Math.Round((newRate.StartTime - oldRate.StartTime).TotalSeconds, 2);long rSpeed = (long)(receive / interval);long sSpeed = (long)(send / interval);return (SizeInfo.Get(rSpeed), SizeInfo.Get(sSpeed));}}

使用

var network = NetworkInfo.TryGetRealNetworkInfo();
var oldRate = network.GetIpv4Speed();
while (true)
{Thread.Sleep(1000);var newRate = network.GetIpv4Speed();var speed = NetworkInfo.GetSpeed(oldRate, newRate);oldRate = newRate;Console.Clear();Console.WriteLine($"上传:{speed.Sent.Size} {speed.Sent.SizeType}/S    下载:{speed.Received.Size} {speed.Received.SizeType}/S");
}

参考

https://www.jb51.net/article/190663.htm
https://blog.csdn.net/chscomfaner/article/details/82784999
https://github.com/ewwink/NetworkSpeed
https://learn.microsoft.com/zh-cn/dotnet/api/system.net.networkinformation.networkinterfacetype?view=netcore-3.1
https://github.com/whuanle/CZGL.SystemInfo

这篇关于C# 获取windows的上传下载速度的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1032522

相关文章

2. c#从不同cs的文件调用函数

1.文件目录如下: 2. Program.cs文件的主函数如下 using System;using System.Collections.Generic;using System.Linq;using System.Threading.Tasks;using System.Windows.Forms;namespace datasAnalysis{internal static

C#实战|大乐透选号器[6]:实现实时显示已选择的红蓝球数量

哈喽,你好啊,我是雷工。 关于大乐透选号器在前面已经记录了5篇笔记,这是第6篇; 接下来实现实时显示当前选中红球数量,蓝球数量; 以下为练习笔记。 01 效果演示 当选择和取消选择红球或蓝球时,在对应的位置显示实时已选择的红球、蓝球的数量; 02 标签名称 分别设置Label标签名称为:lblRedCount、lblBlueCount

用命令行的方式启动.netcore webapi

用命令行的方式启动.netcore web项目 进入指定的项目文件夹,比如我发布后的代码放在下面文件夹中 在此地址栏中输入“cmd”,打开命令提示符,进入到发布代码目录 命令行启动.netcore项目的命令为:  dotnet 项目启动文件.dll --urls="http://*:对外端口" --ip="本机ip" --port=项目内部端口 例: dotnet Imagine.M

在 Windows 上部署 gitblit

在 Windows 上部署 gitblit 在 Windows 上部署 gitblit 缘起gitblit 是什么安装JDK部署 gitblit 下载 gitblit 并解压配置登录注册为 windows 服务 修改 installService.cmd 文件运行 installService.cmd运行 gitblitw.exe查看 services.msc 缘起

Windows如何添加右键新建菜单

Windows如何添加右键新建菜单 文章目录 Windows如何添加右键新建菜单实验环境缘起以新建`.md`文件为例第一步第二步第三步 总结 实验环境 Windows7 缘起 因为我习惯用 Markdown 格式写文本,每次新建一个.txt后都要手动修改为.md,真的麻烦。如何在右键新建菜单中添加.md选项呢? 网上有很多方法,这些方法我都尝试了,要么太麻烦,要么不凑效

Android Environment 获取的路径问题

1. 以获取 /System 路径为例 /*** Return root of the "system" partition holding the core Android OS.* Always present and mounted read-only.*/public static @NonNull File getRootDirectory() {return DIR_ANDR

Windows下Nginx的安装及开机启动

1、将nginx-1.16.1.zip解压拷贝至D:\web\nginx目录下。 2、启动Nginx,两种方法: (1)直接双击nginx.exe,双击后一个黑色的弹窗一闪而过。 (2)打开cmd命令窗口,切换到nginx目录下,输入命令 nginx.exe 或者 start nginx ,回车即可。 3、检查nginx是否启动成功。 直接在浏览器地址栏输入网址 http://lo

C# dateTimePicker 显示年月日,时分秒

dateTimePicker默认只显示日期,如果需要显示年月日,时分秒,只需要以下两步: 1.dateTimePicker1.Format = DateTimePickerFormat.Time 2.dateTimePicker1.CustomFormat = yyyy-MM-dd HH:mm:ss Tips:  a. dateTimePicker1.ShowUpDown = t

C#关闭指定时间段的Excel进程的方法

private DateTime beforeTime;            //Excel启动之前时间          private DateTime afterTime;               //Excel启动之后时间          //举例          beforeTime = DateTime.Now;          Excel.Applicat

C# 防止按钮botton重复“点击”的方法

在使用C#的按钮控件的时候,经常我们想如果出现了多次点击的时候只让其在执行的时候只响应一次。这个时候很多人可能会想到使用Enable=false, 但是实际情况是还是会被多次触发,因为C#采用的是消息队列机制,这个时候我们只需要在Enable = true 之前加一句 Application.DoEvents();就能达到防止重复点击的问题。 private void btnGenerateSh