diff --git a/Masuit.Tools.Abstractions/Hardware/SystemInfo.cs b/Masuit.Tools.Abstractions/Hardware/SystemInfo.cs index 2e4157a1..a105c3ca 100644 --- a/Masuit.Tools.Abstractions/Hardware/SystemInfo.cs +++ b/Masuit.Tools.Abstractions/Hardware/SystemInfo.cs @@ -16,851 +16,852 @@ namespace Masuit.Tools.Hardware { - /// - /// 硬件信息,部分功能需要C++支持,仅支持Windows系统 - /// - public static partial class SystemInfo - { - #region 字段 - - private const int GwHwndfirst = 0; - private const int GwHwndnext = 2; - private const int GwlStyle = -16; - private const int WsVisible = 268435456; - private const int WsBorder = 8388608; - private static readonly PerformanceCounter PcCpuLoad; //CPU计数器 - - private static readonly PerformanceCounter IOCounter; - - private static readonly string[] InstanceNames = { }; - private static readonly PerformanceCounter[] NetRecvCounters; - private static readonly PerformanceCounter[] NetSentCounters; - private static readonly Dictionary Cache = new(); - - public static bool IsWinPlatform => Environment.OSVersion.Platform is PlatformID.Win32Windows - or PlatformID.Win32S or PlatformID.WinCE or PlatformID.Win32NT; - - #endregion 字段 - - #region 构造函数 - - /// - /// 静态构造函数 - /// - static SystemInfo() - { - if (IsWinPlatform) - { - IOCounter = new PerformanceCounter(); - - //初始化CPU计数器 - PcCpuLoad = new PerformanceCounter("Processor", "% Processor Time", "_Total") - { - MachineName = "." - }; - PcCpuLoad.NextValue(); - - //获得物理内存 - try - { - using var mc = new ManagementClass("Win32_ComputerSystem"); - using var moc = mc.GetInstances(); - foreach (var mo in moc) - { - using (mo) - { - if (mo["TotalPhysicalMemory"] != null) - { - PhysicalMemory = mo["TotalPhysicalMemory"].ChangeTypeTo(); - } - } - } - - var cat = new PerformanceCounterCategory("Network Interface"); - InstanceNames = cat.GetInstanceNames(); - NetRecvCounters = new PerformanceCounter[InstanceNames.Length]; - NetSentCounters = new PerformanceCounter[InstanceNames.Length]; - for (int i = 0; i < InstanceNames.Length; i++) - { - NetRecvCounters[i] = new PerformanceCounter(); - NetSentCounters[i] = new PerformanceCounter(); - } - - CompactFormat = false; - } - catch (Exception e) - { - LogManager.Error(e); - } - } - - //CPU个数 - ProcessorCount = Environment.ProcessorCount; - } - - #endregion 构造函数 - - private static bool CompactFormat { get; set; } - - #region CPU相关 - - /// - /// 获取CPU核心数 - /// - public static int ProcessorCount { get; } - - /// - /// 获取CPU占用率 % - /// - public static float CpuLoad => PcCpuLoad?.NextValue() ?? 0; - - /// - /// 获取当前进程的CPU使用率(至少需要0.5s) - /// - /// - public static async Task GetCpuUsageForProcess() - { - var startTime = DateTime.UtcNow; - using var p1 = Process.GetCurrentProcess(); - var startCpuUsage = p1.TotalProcessorTime; - await Task.Delay(500); - var endTime = DateTime.UtcNow; - using var p2 = Process.GetCurrentProcess(); - var endCpuUsage = p2.TotalProcessorTime; - var cpuUsedMs = (endCpuUsage - startCpuUsage).TotalMilliseconds; - var totalMsPassed = (endTime - startTime).TotalMilliseconds; - return cpuUsedMs / (Environment.ProcessorCount * totalMsPassed) * 100; - } - - /// - /// WMI接口获取CPU使用率 - /// - /// - public static string GetProcessorData() - { - var d = GetCounterValue(IOCounter, "Processor", "% Processor Time", "_Total"); - return CompactFormat ? (int)d + "%" : d.ToString("F") + "%"; - } - - /// - /// 获取CPU温度 - /// - /// CPU温度 - public static float GetCPUTemperature() - { - if (!IsWinPlatform) return 0; - - try - { - using var mos = new ManagementObjectSearcher(@"root\WMI", "select * from MSAcpi_ThermalZoneTemperature"); - using var moc = mos.Get(); - foreach (var mo in moc) - { - using (mo) - { - //这就是CPU的温度了 - var temp = (mo["CurrentTemperature"].ChangeTypeTo() - 2732) / 10; - return (float)Math.Round(temp, 2); - } - } - return 0; - } - catch (Exception) - { - return -1; - } - } - - /// - /// 获取CPU的数量 - /// - /// CPU的数量 - public static int GetCpuCount() - { - try - { - return Cache.GetOrAdd(nameof(GetCpuCount), () => - { - if (!IsWinPlatform) - { - return Environment.ProcessorCount; - } - - using var m = new ManagementClass("Win32_Processor"); - using var moc = m.GetInstances(); - return moc.Count; - }); - } - catch (Exception) - { - return -1; - } - } - - private static readonly Lazy> CpuObjects = new(() => - { - using var mos = new ManagementObjectSearcher("SELECT * FROM Win32_Processor"); - using var moc = mos.Get(); - return moc.AsParallel().Cast().ToList(); - }); - - /// - /// 获取CPU信息 - /// - /// CPU信息 - public static List GetCpuInfo() - { - try - { - if (!IsWinPlatform) return []; - return CpuObjects.Value.Select(mo => new CpuInfo - { - NumberOfLogicalProcessors = ProcessorCount, - CurrentClockSpeed = mo["CurrentClockSpeed"].ToString(), - Manufacturer = mo["Manufacturer"].ToString(), - MaxClockSpeed = mo["MaxClockSpeed"].ToString(), - Type = mo["Name"].ToString(), - DataWidth = mo["DataWidth"].ToString(), - SerialNumber = mo["ProcessorId"].ToString(), - DeviceID = mo["DeviceID"].ToString(), - NumberOfCores = mo["NumberOfCores"].ChangeTypeTo() - }).ToList(); - } - catch (Exception) - { - return []; - } - } + /// + /// 硬件信息,部分功能需要C++支持,仅支持Windows系统 + /// + public static partial class SystemInfo + { + #region 字段 + + private const int GwHwndfirst = 0; + private const int GwHwndnext = 2; + private const int GwlStyle = -16; + private const int WsVisible = 268435456; + private const int WsBorder = 8388608; + private static readonly PerformanceCounter PcCpuLoad; //CPU计数器 + + private static readonly PerformanceCounter IOCounter; + + private static readonly string[] InstanceNames = { }; + private static readonly PerformanceCounter[] NetRecvCounters; + private static readonly PerformanceCounter[] NetSentCounters; + private static readonly Dictionary Cache = new(); + + public static bool IsWinPlatform => Environment.OSVersion.Platform is PlatformID.Win32Windows or PlatformID.Win32S or PlatformID.WinCE or PlatformID.Win32NT; + + #endregion 字段 + + #region 构造函数 + + /// + /// 静态构造函数 + /// + static SystemInfo() + { + if (IsWinPlatform) + { + IOCounter = new PerformanceCounter(); + + //初始化CPU计数器 + PcCpuLoad = new PerformanceCounter("Processor", "% Processor Time", "_Total") + { + MachineName = "." + }; + PcCpuLoad.NextValue(); + + //获得物理内存 + try + { + using var mc = new ManagementClass("Win32_ComputerSystem"); + using var moc = mc.GetInstances(); + foreach (var mo in moc) + { + using (mo) + { + if (mo["TotalPhysicalMemory"] != null) + { + PhysicalMemory = mo["TotalPhysicalMemory"].ChangeTypeTo(); + } + } + } + + var cat = new PerformanceCounterCategory("Network Interface"); + InstanceNames = cat.GetInstanceNames(); + NetRecvCounters = new PerformanceCounter[InstanceNames.Length]; + NetSentCounters = new PerformanceCounter[InstanceNames.Length]; + for (int i = 0; i < InstanceNames.Length; i++) + { + NetRecvCounters[i] = new PerformanceCounter(); + NetSentCounters[i] = new PerformanceCounter(); + } + + CompactFormat = false; + } + catch (Exception e) + { + LogManager.Error(e); + } + } + + //CPU个数 + ProcessorCount = Environment.ProcessorCount; + } + + #endregion 构造函数 + + private static bool CompactFormat { get; set; } + + #region CPU相关 + + /// + /// 获取CPU核心数 + /// + public static int ProcessorCount { get; } + + /// + /// 获取CPU占用率 % + /// + public static float CpuLoad => PcCpuLoad?.NextValue() ?? 0; + + /// + /// 获取当前进程的CPU使用率(至少需要0.5s) + /// + /// + public static async Task GetCpuUsageForProcess() + { + var startTime = DateTime.UtcNow; + using var p1 = Process.GetCurrentProcess(); + var startCpuUsage = p1.TotalProcessorTime; + await Task.Delay(500); + var endTime = DateTime.UtcNow; + using var p2 = Process.GetCurrentProcess(); + var endCpuUsage = p2.TotalProcessorTime; + var cpuUsedMs = (endCpuUsage - startCpuUsage).TotalMilliseconds; + var totalMsPassed = (endTime - startTime).TotalMilliseconds; + return cpuUsedMs / (Environment.ProcessorCount * totalMsPassed) * 100; + } + + /// + /// WMI接口获取CPU使用率 + /// + /// + public static string GetProcessorData() + { + var d = GetCounterValue(IOCounter, "Processor", "% Processor Time", "_Total"); + return CompactFormat ? (int)d + "%" : d.ToString("F") + "%"; + } + + /// + /// 获取CPU温度 + /// + /// CPU温度 + public static float GetCPUTemperature() + { + if (!IsWinPlatform) return 0; + + try + { + using var mos = new ManagementObjectSearcher(@"root\WMI", "select * from MSAcpi_ThermalZoneTemperature"); + using var moc = mos.Get(); + foreach (var mo in moc) + { + using (mo) + { + //这就是CPU的温度了 + var temp = (mo["CurrentTemperature"].ChangeTypeTo() - 2732) / 10; + return (float)Math.Round(temp, 2); + } + } + + return 0; + } + catch (Exception) + { + return -1; + } + } + + /// + /// 获取CPU的数量 + /// + /// CPU的数量 + public static int GetCpuCount() + { + try + { + return Cache.GetOrAdd(nameof(GetCpuCount), () => + { + if (!IsWinPlatform) + { + return Environment.ProcessorCount; + } + + using var m = new ManagementClass("Win32_Processor"); + using var moc = m.GetInstances(); + return moc.Count; + }); + } + catch (Exception) + { + return -1; + } + } + + private static readonly Lazy> CpuObjects = new(() => + { + using var mos = new ManagementObjectSearcher("SELECT * FROM Win32_Processor"); + using var moc = mos.Get(); + return moc.AsParallel().Cast().ToList(); + }); + + /// + /// 获取CPU信息 + /// + /// CPU信息 + public static List GetCpuInfo() + { + try + { + if (!IsWinPlatform) return []; + return CpuObjects.Value.Select(mo => new CpuInfo + { + NumberOfLogicalProcessors = ProcessorCount, + CurrentClockSpeed = mo["CurrentClockSpeed"].ToString(), + Manufacturer = mo["Manufacturer"].ToString(), + MaxClockSpeed = mo["MaxClockSpeed"].ToString(), + Type = mo["Name"].ToString(), + DataWidth = mo["DataWidth"].ToString(), + SerialNumber = mo["ProcessorId"].ToString(), + DeviceID = mo["DeviceID"].ToString(), + NumberOfCores = mo["NumberOfCores"].ChangeTypeTo() + }).ToList(); + } + catch (Exception) + { + return []; + } + } #if NET5_0_OR_GREATER - public static string GetCpuId() - { - if (System.Runtime.Intrinsics.X86.X86Base.IsSupported) - { - var (eax, ebx, ecx, edx) = System.Runtime.Intrinsics.X86.X86Base.CpuId(1, 0); - return edx.ToString("X").PadLeft(8, '0') + eax.ToString("X").PadLeft(8, '0'); - } - return null; - } + public static string GetCpuId() + { + if (System.Runtime.Intrinsics.X86.X86Base.IsSupported) + { + var (eax, ebx, ecx, edx) = System.Runtime.Intrinsics.X86.X86Base.CpuId(1, 0); + return edx.ToString("X").PadLeft(8, '0') + eax.ToString("X").PadLeft(8, '0'); + } + return null; + } #endif - #endregion CPU相关 - - #region 内存相关 - - /// - /// 获取可用内存 - /// - public static long MemoryAvailable - { - get - { - if (!IsWinPlatform) return 0; - - try - { - using var mc = new ManagementClass("Win32_OperatingSystem"); - using var moc = mc.GetInstances(); - foreach (var mo in moc) - { - using (mo) - { - if (mo["FreePhysicalMemory"] != null) - { - return 1024 * mo["FreePhysicalMemory"].ChangeTypeTo(); - } - } - } - - return 0; - } - catch (Exception) - { - return -1; - } - } - } - - /// - /// 获取物理内存 - /// - public static long PhysicalMemory { get; } - - public static long CurrentProcessMemory - { - get - { - using var process = Process.GetCurrentProcess(); - return (long)GetCounterValue(IOCounter, "Process", "Working Set - Private", process.ProcessName); - } - } - - /// - /// 获取内存信息 - /// - /// 内存信息 - public static RamInfo GetRamInfo() - { - return new RamInfo - { - MemoryAvailable = GetFreePhysicalMemory(), - PhysicalMemory = GetTotalPhysicalMemory(), - TotalPageFile = GetTotalVirtualMemory(), - AvailablePageFile = GetTotalVirtualMemory() - GetUsedVirtualMemory(), - AvailableVirtual = 1 - GetUsageVirtualMemory(), - TotalVirtual = 1 - GetUsedPhysicalMemory() - }; - } - - /// - /// 获取虚拟内存使用率详情 - /// - /// - public static string GetMemoryVData() - { - if (!IsWinPlatform) return ""; - float d = GetCounterValue(IOCounter, "Memory", "% Committed Bytes In Use", null); - var str = d.ToString("F") + "% ("; - d = GetCounterValue(IOCounter, "Memory", "Committed Bytes", null); - str += FormatBytes(d) + " / "; - d = GetCounterValue(IOCounter, "Memory", "Commit Limit", null); - return str + FormatBytes(d) + ") "; - } - - /// - /// 获取虚拟内存使用率 - /// - /// - public static float GetUsageVirtualMemory() - { - return GetCounterValue(IOCounter, "Memory", "% Committed Bytes In Use", null); - } - - /// - /// 获取虚拟内存已用大小 - /// - /// - public static float GetUsedVirtualMemory() - { - return GetCounterValue(IOCounter, "Memory", "Committed Bytes", null); - } - - /// - /// 获取虚拟内存总大小 - /// - /// - public static float GetTotalVirtualMemory() - { - return GetCounterValue(IOCounter, "Memory", "Commit Limit", null); - } - - /// - /// 获取物理内存使用率详情描述 - /// - /// - public static string GetMemoryPData() - { - if (!IsWinPlatform) return ""; - string s = QueryComputerSystem("totalphysicalmemory"); - if (string.IsNullOrEmpty(s)) return ""; - - var totalphysicalmemory = Convert.ToSingle(s); - var d = GetCounterValue(IOCounter, "Memory", "Available Bytes", null); - d = totalphysicalmemory - d; - s = CompactFormat ? "%" : "% (" + FormatBytes(d) + " / " + FormatBytes(totalphysicalmemory) + ")"; - d /= totalphysicalmemory; - d *= 100; - return CompactFormat ? (int)d + s : d.ToString("F") + s; - } - - /// - /// 获取物理内存总数,单位B - /// - /// - public static float GetTotalPhysicalMemory() - { - return Cache.GetOrAdd(nameof(GetTotalPhysicalMemory), () => - { - var s = QueryComputerSystem("totalphysicalmemory"); - return s.TryConvertTo(); - }); - } - - /// - /// 获取空闲的物理内存数,单位B - /// - /// - public static float GetFreePhysicalMemory() - { - return GetCounterValue(IOCounter, "Memory", "Available Bytes", null); - } - - /// - /// 获取已经使用了的物理内存数,单位B - /// - /// - public static float GetUsedPhysicalMemory() - { - return GetTotalPhysicalMemory() - GetFreePhysicalMemory(); - } - - #endregion 内存相关 - - #region 硬盘相关 - - /// - /// 获取硬盘的读写速率 - /// - /// 读或写 - /// - public static float GetDiskData(DiskData dd) - { - return dd switch - { - DiskData.Read => GetCounterValue(IOCounter, "PhysicalDisk", "Disk Read Bytes/sec", "_Total"), - DiskData.Write => GetCounterValue(IOCounter, "PhysicalDisk", "Disk Write Bytes/sec", "_Total"), - DiskData.ReadAndWrite => GetCounterValue(IOCounter, "PhysicalDisk", "Disk Read Bytes/sec", "_Total") + GetCounterValue(IOCounter, "PhysicalDisk", "Disk Write Bytes/sec", "_Total"), - _ => 0 - }; - } - - private static List _diskInfos = []; - - /// - /// 获取磁盘可用空间 - /// - /// - public static List GetDiskInfo() - { - try - { - if (!IsWinPlatform || _diskInfos.Count > 0) - { - return _diskInfos; - } - - using var mc = new ManagementClass("Win32_DiskDrive"); - using var moc = mc.GetInstances(); - var list = new List(); - foreach (var mo in moc) - { - using (mo) - { - list.Add(new DiskInfo() - { - Index = mo["Index"].ChangeTypeTo(), - Total = mo["Size"].ChangeTypeTo(), - Model = mo["Model"].ToString(), - MediaType = mo["MediaType"].ToString(), - SerialNumber = mo["SerialNumber"].ToString(), - }); - } - } - - _diskInfos = list.OrderBy(x => x.Index).ToList(); - return _diskInfos; - } - catch (Exception) - { - return []; - } - } - - #endregion 硬盘相关 - - #region 网络相关 - - /// - /// 获取网络的传输速率 - /// - /// 上传或下载 - /// - public static float GetNetData(NetData nd) - { - if (!IsWinPlatform) return 0; - if (InstanceNames is { Length: 0 }) return 0; - - float d = 0; - for (int i = 0; i < InstanceNames.Length; i++) - { - float receied = GetCounterValue(NetRecvCounters[i], "Network Interface", "Bytes Received/sec", InstanceNames[i]); - float send = GetCounterValue(NetSentCounters[i], "Network Interface", "Bytes Sent/sec", InstanceNames[i]); - switch (nd) - { - case NetData.Received: - d += receied; - break; - - case NetData.Sent: - d += send; - break; - - case NetData.ReceivedAndSent: - d += receied + send; - break; - - default: - d += 0; - break; - } - } - - return d; - } - - /// - /// 获取网卡硬件地址 - /// - /// - public static IEnumerable GetMacAddress() - { - return from adapter in NetworkInterface.GetAllNetworkInterfaces().Where(c => c.NetworkInterfaceType != NetworkInterfaceType.Loopback && c.OperationalStatus == OperationalStatus.Up) - let properties = adapter.GetIPProperties() - let unicastAddresses = properties.UnicastAddresses - where unicastAddresses.Any(temp => temp.Address.AddressFamily == AddressFamily.InterNetwork) - select adapter.GetPhysicalAddress() into address - select address; - } - - /// - /// 获取IP地址WMI - /// - /// - public static string GetIPAddressWMI() - { - try - { - if (!IsWinPlatform) return ""; - - return Cache.GetOrAdd(nameof(GetIPAddressWMI), () => - { - using var mc = new ManagementClass("Win32_NetworkAdapterConfiguration"); - using var moc = mc.GetInstances(); - foreach (var mo in moc) - { - if ((bool)mo["IPEnabled"]) - { - return ((string[])mo["IpAddress"])[0]; - } - } - return ""; - }); - } - catch (Exception e) - { - Console.WriteLine(e.Message); - } - - return ""; - } - - /// - /// 获取当前使用的IP - /// - /// - public static IPAddress GetLocalUsedIP() - { - return GetLocalUsedIP(AddressFamily.InterNetwork); - } - - /// - /// 获取当前使用的IP - /// - /// - public static IPAddress GetLocalUsedIP(AddressFamily family) - { - return NetworkInterface.GetAllNetworkInterfaces().Where(c => c.NetworkInterfaceType != NetworkInterfaceType.Loopback && c.OperationalStatus == OperationalStatus.Up).OrderByDescending(c => c.Speed).Select(t => t.GetIPProperties()).Where(p => p.DhcpServerAddresses.Count > 0).SelectMany(p => p.UnicastAddresses).Select(p => p.Address).FirstOrDefault(p => !(p.IsIPv6Teredo || p.IsIPv6LinkLocal || p.IsIPv6Multicast || p.IsIPv6SiteLocal) && p.AddressFamily == family); - } - - /// - /// 获取本机所有的ip地址 - /// - /// - public static List GetLocalIPs() - { - var interfaces = NetworkInterface.GetAllNetworkInterfaces().Where(c => c.NetworkInterfaceType != NetworkInterfaceType.Loopback && c.OperationalStatus == OperationalStatus.Up).OrderByDescending(c => c.Speed); //所有网卡信息 - return interfaces.SelectMany(n => n.GetIPProperties().UnicastAddresses).ToList(); - } - - /// - /// 获取网卡地址 - /// - /// - public static string GetNetworkCardAddress() - { - try - { - if (!IsWinPlatform) return ""; - - return Cache.GetOrAdd(nameof(GetNetworkCardAddress), () => - { - using var mos = new ManagementObjectSearcher("select * from Win32_NetworkAdapter where ((MACAddress Is Not NULL) and (Manufacturer <> 'Microsoft'))"); - using var moc = mos.Get(); - foreach (var mo in moc) - { - return mo["MACAddress"].ToString().Trim(); - } - return ""; - }); - } - catch (Exception e) - { - Console.WriteLine(e.Message); - } - - return ""; - } - - #endregion 网络相关 - - #region 系统相关 - - /// - /// 获取计算机开机时间 - /// - /// datetime - public static DateTime BootTime() - { - if (!IsWinPlatform) return default; - - var query = new SelectQuery("SELECT LastBootUpTime FROM Win32_OperatingSystem WHERE Primary='true'"); - using var searcher = new ManagementObjectSearcher(query); - using var moc = searcher.Get(); - foreach (var mo in moc) - { - using (mo) - { - return ManagementDateTimeConverter.ToDateTime(mo["LastBootUpTime"].ToString()); - } - } - - return DateTime.Now - TimeSpan.FromMilliseconds(Environment.TickCount & int.MaxValue); - } - - /// - /// 查询计算机系统信息 - /// - /// 类型名 - /// - public static string QueryComputerSystem(string type) - { - try - { - if (!IsWinPlatform) return string.Empty; - - var mos = new ManagementObjectSearcher("SELECT * FROM Win32_ComputerSystem"); - using var moc = mos.Get(); - foreach (var mo in moc) - { - using (mo) - { - return mo[type].ToString(); - } - } - } - catch (Exception e) - { - return "未能获取到当前计算机系统信息,可能是当前程序无管理员权限,如果是web应用程序,请将应用程序池的高级设置中的进程模型下的标识设置为:LocalSystem;如果是普通桌面应用程序,请提升管理员权限后再操作。异常信息:" + e.Message; - } - return string.Empty; - } - - /// - /// 查找所有应用程序标题 - /// - /// 应用程序标题范型 - /// 所有应用程序集合 - public static List FindAllApps(int handle) - { - if (!IsWinPlatform) return new List(0); - - var apps = new List(); - int hwCurr = GetWindow(handle, GwHwndfirst); - while (hwCurr > 0) - { - int IsTask = WsVisible | WsBorder; - int lngStyle = GetWindowLongA(hwCurr, GwlStyle); - bool taskWindow = (lngStyle & IsTask) == IsTask; - if (taskWindow) - { - int length = GetWindowTextLength(new IntPtr(hwCurr)); - var sb = new StringBuilder(2 * length + 1); - GetWindowText(hwCurr, sb, sb.Capacity); - string strTitle = sb.ToString(); - if (!string.IsNullOrEmpty(strTitle)) - { - apps.Add(strTitle); - } - } - - hwCurr = GetWindow(hwCurr, GwHwndnext); - } - - return apps; - } - - /// - /// 操作系统类型 - /// - /// - public static string GetSystemType() - { - try - { - return Cache.GetOrAdd(nameof(GetSystemType), () => - { - if (!IsWinPlatform) - { - return Environment.OSVersion.Platform.ToString(); - } - - using var mc = new ManagementClass("Win32_ComputerSystem"); - using var moc = mc.GetInstances(); - foreach (var mo in moc) - { - return mo["SystemType"].ToString().Trim(); - } - return ""; - }); - } - catch (Exception e) - { - Console.WriteLine(e.Message); - } - - return ""; - } - - #endregion 系统相关 - - #region 主板相关 - - /// - /// 获取主板序列号 - /// - /// - public static string GetBiosSerialNumber() - { - try - { - if (!IsWinPlatform) return ""; - - return Cache.GetOrAdd(nameof(GetBiosSerialNumber), () => - { - using var searcher = new ManagementObjectSearcher("select * from Win32_BIOS"); - using var mos = searcher.Get(); - foreach (var mo in mos) - { - return mo["SerialNumber"].ToString().Trim(); - } - return ""; - }); - } - catch (Exception e) - { - Console.WriteLine(e.Message); - } - - return ""; - } - - /// - /// 主板编号 - /// - /// - public static BiosInfo GetBiosInfo() - { - if (!IsWinPlatform) return new BiosInfo(); - - return Cache.GetOrAdd(nameof(GetBiosInfo), () => - { - using var searcher = new ManagementObjectSearcher("select * from Win32_BaseBoard"); - using var mos = searcher.Get(); - using var reg = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64); - using var guidKey = reg.OpenSubKey(@"SOFTWARE\Microsoft\Cryptography"); - using var uuidKey = reg.OpenSubKey(@"SYSTEM\HardwareConfig"); - string guid = null; - string uuid = null; - string model = null; - if (guidKey != null) guid = guidKey.GetValue("MachineGuid") + ""; - if (uuidKey != null) uuid = (uuidKey.GetValue("LastConfig") + "").Trim('{', '}').ToUpper(); - var biosKey = Registry.LocalMachine.OpenSubKey(@"HARDWARE\DESCRIPTION\System\BIOS"); - biosKey ??= Registry.LocalMachine.OpenSubKey(@"SYSTEM\HardwareConfig\Current"); - if (biosKey != null) - { - model = (biosKey.GetValue("SystemProductName") + "").Replace("System Product Name", null); - if (model.IsNullOrEmpty()) model = biosKey.GetValue("BaseBoardProduct") + ""; - biosKey.Dispose(); - } - foreach (var mo in mos) - { - return new BiosInfo - { - Manufacturer = mo["Manufacturer"].ToString(), - ID = mo["SerialNumber"].ToString(), - Model = model, - SerialNumber = GetBiosSerialNumber(), - Guid = guid, - UUID = uuid - }; - } - - return new BiosInfo(); - }); - } - - #endregion 主板相关 - - #region 公共函数 - - /// - /// 将速度值格式化成字节单位 - /// - /// - /// - public static string FormatBytes(this double bytes) - { - int unit = 0; - while (bytes > 1024) - { - bytes /= 1024; - ++unit; - } - - string s = CompactFormat ? ((int)bytes).ToString() : bytes.ToString("F") + " "; - return s + (Unit)unit; - } - - private static float GetCounterValue(PerformanceCounter pc, string categoryName, string counterName, string instanceName) - { - if (!IsWinPlatform) return 0; - - pc.CategoryName = categoryName; - pc.CounterName = counterName; - pc.InstanceName = instanceName; - return pc.NextValue(); - } - - #endregion 公共函数 - - #region Win32API声明 + #endregion CPU相关 + + #region 内存相关 + + /// + /// 获取可用内存 + /// + public static long MemoryAvailable + { + get + { + if (!IsWinPlatform) return 0; + + try + { + using var mc = new ManagementClass("Win32_OperatingSystem"); + using var moc = mc.GetInstances(); + foreach (var mo in moc) + { + using (mo) + { + if (mo["FreePhysicalMemory"] != null) + { + return 1024 * mo["FreePhysicalMemory"].ChangeTypeTo(); + } + } + } + + return 0; + } + catch (Exception) + { + return -1; + } + } + } + + /// + /// 获取物理内存 + /// + public static long PhysicalMemory { get; } + + public static long CurrentProcessMemory + { + get + { + using var process = Process.GetCurrentProcess(); + return (long)GetCounterValue(IOCounter, "Process", "Working Set - Private", process.ProcessName); + } + } + + /// + /// 获取内存信息 + /// + /// 内存信息 + public static RamInfo GetRamInfo() + { + return new RamInfo + { + MemoryAvailable = GetFreePhysicalMemory(), + PhysicalMemory = GetTotalPhysicalMemory(), + TotalPageFile = GetTotalVirtualMemory(), + AvailablePageFile = GetTotalVirtualMemory() - GetUsedVirtualMemory(), + AvailableVirtual = 1 - GetUsageVirtualMemory(), + TotalVirtual = 1 - GetUsedPhysicalMemory() + }; + } + + /// + /// 获取虚拟内存使用率详情 + /// + /// + public static string GetMemoryVData() + { + if (!IsWinPlatform) return ""; + float d = GetCounterValue(IOCounter, "Memory", "% Committed Bytes In Use", null); + var str = d.ToString("F") + "% ("; + d = GetCounterValue(IOCounter, "Memory", "Committed Bytes", null); + str += FormatBytes(d) + " / "; + d = GetCounterValue(IOCounter, "Memory", "Commit Limit", null); + return str + FormatBytes(d) + ") "; + } + + /// + /// 获取虚拟内存使用率 + /// + /// + public static float GetUsageVirtualMemory() + { + return GetCounterValue(IOCounter, "Memory", "% Committed Bytes In Use", null); + } + + /// + /// 获取虚拟内存已用大小 + /// + /// + public static float GetUsedVirtualMemory() + { + return GetCounterValue(IOCounter, "Memory", "Committed Bytes", null); + } + + /// + /// 获取虚拟内存总大小 + /// + /// + public static float GetTotalVirtualMemory() + { + return GetCounterValue(IOCounter, "Memory", "Commit Limit", null); + } + + /// + /// 获取物理内存使用率详情描述 + /// + /// + public static string GetMemoryPData() + { + if (!IsWinPlatform) return ""; + string s = QueryComputerSystem("totalphysicalmemory"); + if (string.IsNullOrEmpty(s)) return ""; + + var totalphysicalmemory = Convert.ToSingle(s); + var d = GetCounterValue(IOCounter, "Memory", "Available Bytes", null); + d = totalphysicalmemory - d; + s = CompactFormat ? "%" : "% (" + FormatBytes(d) + " / " + FormatBytes(totalphysicalmemory) + ")"; + d /= totalphysicalmemory; + d *= 100; + return CompactFormat ? (int)d + s : d.ToString("F") + s; + } + + /// + /// 获取物理内存总数,单位B + /// + /// + public static float GetTotalPhysicalMemory() + { + return Cache.GetOrAdd(nameof(GetTotalPhysicalMemory), () => + { + var s = QueryComputerSystem("totalphysicalmemory"); + return s.TryConvertTo(); + }); + } + + /// + /// 获取空闲的物理内存数,单位B + /// + /// + public static float GetFreePhysicalMemory() + { + return GetCounterValue(IOCounter, "Memory", "Available Bytes", null); + } + + /// + /// 获取已经使用了的物理内存数,单位B + /// + /// + public static float GetUsedPhysicalMemory() + { + return GetTotalPhysicalMemory() - GetFreePhysicalMemory(); + } + + #endregion 内存相关 + + #region 硬盘相关 + + /// + /// 获取硬盘的读写速率 + /// + /// 读或写 + /// + public static float GetDiskData(DiskData dd) + { + return dd switch + { + DiskData.Read => GetCounterValue(IOCounter, "PhysicalDisk", "Disk Read Bytes/sec", "_Total"), + DiskData.Write => GetCounterValue(IOCounter, "PhysicalDisk", "Disk Write Bytes/sec", "_Total"), + DiskData.ReadAndWrite => GetCounterValue(IOCounter, "PhysicalDisk", "Disk Read Bytes/sec", "_Total") + GetCounterValue(IOCounter, "PhysicalDisk", "Disk Write Bytes/sec", "_Total"), + _ => 0 + }; + } + + private static List _diskInfos = []; + + /// + /// 获取磁盘可用空间 + /// + /// + public static List GetDiskInfo() + { + try + { + if (!IsWinPlatform || _diskInfos.Count > 0) + { + return _diskInfos; + } + + using var mc = new ManagementClass("Win32_DiskDrive"); + using var moc = mc.GetInstances(); + var list = new List(); + foreach (var mo in moc) + { + using (mo) + { + list.Add(new DiskInfo() + { + Index = mo["Index"].ChangeTypeTo(), + Total = mo["Size"].ChangeTypeTo(), + Model = mo["Model"].ToString(), + MediaType = mo["MediaType"].ToString(), + SerialNumber = mo["SerialNumber"].ToString(), + }); + } + } + + _diskInfos = list.OrderBy(x => x.Index).ToList(); + return _diskInfos; + } + catch (Exception) + { + return []; + } + } + + #endregion 硬盘相关 + + #region 网络相关 + + /// + /// 获取网络的传输速率 + /// + /// 上传或下载 + /// + public static float GetNetData(NetData nd) + { + if (!IsWinPlatform) return 0; + if (InstanceNames is { Length: 0 }) return 0; + + float d = 0; + for (int i = 0; i < InstanceNames.Length; i++) + { + float receied = GetCounterValue(NetRecvCounters[i], "Network Interface", "Bytes Received/sec", InstanceNames[i]); + float send = GetCounterValue(NetSentCounters[i], "Network Interface", "Bytes Sent/sec", InstanceNames[i]); + switch (nd) + { + case NetData.Received: + d += receied; + break; + + case NetData.Sent: + d += send; + break; + + case NetData.ReceivedAndSent: + d += receied + send; + break; + + default: + d += 0; + break; + } + } + + return d; + } + + /// + /// 获取网卡硬件地址 + /// + /// + public static IEnumerable GetMacAddress() + { + return NetworkInterface.GetAllNetworkInterfaces().Where(c => c.NetworkInterfaceType != NetworkInterfaceType.Loopback && c.OperationalStatus == OperationalStatus.Up && c.GetIPProperties().UnicastAddresses.Any(temp => temp.Address.AddressFamily is AddressFamily.InterNetwork or AddressFamily.InterNetworkV6)).Select(c => c.GetPhysicalAddress()); + } + + /// + /// 获取IP地址WMI + /// + /// + public static string GetIPAddressWMI() + { + try + { + if (!IsWinPlatform) return ""; + + return Cache.GetOrAdd(nameof(GetIPAddressWMI), () => + { + using var mc = new ManagementClass("Win32_NetworkAdapterConfiguration"); + using var moc = mc.GetInstances(); + foreach (var mo in moc) + { + if ((bool)mo["IPEnabled"]) + { + return ((string[])mo["IpAddress"])[0]; + } + } + + return ""; + }); + } + catch (Exception e) + { + Console.WriteLine(e.Message); + } + + return ""; + } + + /// + /// 获取当前使用的IP + /// + /// + public static IPAddress GetLocalUsedIP() + { + return GetLocalUsedIP(AddressFamily.InterNetwork); + } + + /// + /// 获取当前使用的IP + /// + /// + public static IPAddress GetLocalUsedIP(AddressFamily family) + { + return NetworkInterface.GetAllNetworkInterfaces().Where(c => c.NetworkInterfaceType != NetworkInterfaceType.Loopback && c.OperationalStatus == OperationalStatus.Up).OrderByDescending(c => c.Speed).Select(t => t.GetIPProperties()).Where(p => p.DhcpServerAddresses.Count > 0).SelectMany(p => p.UnicastAddresses).Select(p => p.Address).FirstOrDefault(p => !(p.IsIPv6Teredo || p.IsIPv6LinkLocal || p.IsIPv6Multicast || p.IsIPv6SiteLocal) && p.AddressFamily == family); + } + + /// + /// 获取本机所有的ip地址 + /// + /// + public static List GetLocalIPs() + { + var interfaces = NetworkInterface.GetAllNetworkInterfaces().Where(c => c.NetworkInterfaceType != NetworkInterfaceType.Loopback && c.OperationalStatus == OperationalStatus.Up).OrderByDescending(c => c.Speed); //所有网卡信息 + return interfaces.SelectMany(n => n.GetIPProperties().UnicastAddresses).ToList(); + } + + /// + /// 获取网卡地址 + /// + /// + public static string GetNetworkCardAddress() + { + try + { + if (!IsWinPlatform) return ""; + + return Cache.GetOrAdd(nameof(GetNetworkCardAddress), () => + { + using var mos = new ManagementObjectSearcher("select * from Win32_NetworkAdapter where ((MACAddress Is Not NULL) and (Manufacturer <> 'Microsoft'))"); + using var moc = mos.Get(); + foreach (var mo in moc) + { + return mo["MACAddress"].ToString().Trim(); + } + + return ""; + }); + } + catch (Exception e) + { + Console.WriteLine(e.Message); + } + + return ""; + } + + #endregion 网络相关 + + #region 系统相关 + + /// + /// 获取计算机开机时间 + /// + /// datetime + public static DateTime BootTime() + { + if (!IsWinPlatform) return default; + + var query = new SelectQuery("SELECT LastBootUpTime FROM Win32_OperatingSystem WHERE Primary='true'"); + using var searcher = new ManagementObjectSearcher(query); + using var moc = searcher.Get(); + foreach (var mo in moc) + { + using (mo) + { + return ManagementDateTimeConverter.ToDateTime(mo["LastBootUpTime"].ToString()); + } + } + + return DateTime.Now - TimeSpan.FromMilliseconds(Environment.TickCount & int.MaxValue); + } + + /// + /// 查询计算机系统信息 + /// + /// 类型名 + /// + public static string QueryComputerSystem(string type) + { + try + { + if (!IsWinPlatform) return string.Empty; + + var mos = new ManagementObjectSearcher("SELECT * FROM Win32_ComputerSystem"); + using var moc = mos.Get(); + foreach (var mo in moc) + { + using (mo) + { + return mo[type].ToString(); + } + } + } + catch (Exception e) + { + return "未能获取到当前计算机系统信息,可能是当前程序无管理员权限,如果是web应用程序,请将应用程序池的高级设置中的进程模型下的标识设置为:LocalSystem;如果是普通桌面应用程序,请提升管理员权限后再操作。异常信息:" + e.Message; + } + + return string.Empty; + } + + /// + /// 查找所有应用程序标题 + /// + /// 应用程序标题范型 + /// 所有应用程序集合 + public static List FindAllApps(int handle) + { + if (!IsWinPlatform) return new List(0); + + var apps = new List(); + int hwCurr = GetWindow(handle, GwHwndfirst); + while (hwCurr > 0) + { + int IsTask = WsVisible | WsBorder; + int lngStyle = GetWindowLongA(hwCurr, GwlStyle); + bool taskWindow = (lngStyle & IsTask) == IsTask; + if (taskWindow) + { + int length = GetWindowTextLength(new IntPtr(hwCurr)); + var sb = new StringBuilder(2 * length + 1); + GetWindowText(hwCurr, sb, sb.Capacity); + string strTitle = sb.ToString(); + if (!string.IsNullOrEmpty(strTitle)) + { + apps.Add(strTitle); + } + } + + hwCurr = GetWindow(hwCurr, GwHwndnext); + } + + return apps; + } + + /// + /// 操作系统类型 + /// + /// + public static string GetSystemType() + { + try + { + return Cache.GetOrAdd(nameof(GetSystemType), () => + { + if (!IsWinPlatform) + { + return Environment.OSVersion.Platform.ToString(); + } + + using var mc = new ManagementClass("Win32_ComputerSystem"); + using var moc = mc.GetInstances(); + foreach (var mo in moc) + { + return mo["SystemType"].ToString().Trim(); + } + + return ""; + }); + } + catch (Exception e) + { + Console.WriteLine(e.Message); + } + + return ""; + } + + #endregion 系统相关 + + #region 主板相关 + + /// + /// 获取主板序列号 + /// + /// + public static string GetBiosSerialNumber() + { + try + { + if (!IsWinPlatform) return ""; + + return Cache.GetOrAdd(nameof(GetBiosSerialNumber), () => + { + using var searcher = new ManagementObjectSearcher("select * from Win32_BIOS"); + using var mos = searcher.Get(); + foreach (var mo in mos) + { + return mo["SerialNumber"].ToString().Trim(); + } + + return ""; + }); + } + catch (Exception e) + { + Console.WriteLine(e.Message); + } + + return ""; + } + + /// + /// 主板编号 + /// + /// + public static BiosInfo GetBiosInfo() + { + if (!IsWinPlatform) return new BiosInfo(); + + return Cache.GetOrAdd(nameof(GetBiosInfo), () => + { + using var searcher = new ManagementObjectSearcher("select * from Win32_BaseBoard"); + using var mos = searcher.Get(); + using var reg = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64); + using var guidKey = reg.OpenSubKey(@"SOFTWARE\Microsoft\Cryptography"); + using var uuidKey = reg.OpenSubKey(@"SYSTEM\HardwareConfig"); + string guid = null; + string uuid = null; + string model = null; + if (guidKey != null) guid = guidKey.GetValue("MachineGuid") + ""; + if (uuidKey != null) uuid = (uuidKey.GetValue("LastConfig") + "").Trim('{', '}').ToUpper(); + var biosKey = Registry.LocalMachine.OpenSubKey(@"HARDWARE\DESCRIPTION\System\BIOS"); + biosKey ??= Registry.LocalMachine.OpenSubKey(@"SYSTEM\HardwareConfig\Current"); + if (biosKey != null) + { + model = (biosKey.GetValue("SystemProductName") + "").Replace("System Product Name", null); + if (model.IsNullOrEmpty()) model = biosKey.GetValue("BaseBoardProduct") + ""; + biosKey.Dispose(); + } + + foreach (var mo in mos) + { + return new BiosInfo + { + Manufacturer = mo["Manufacturer"].ToString(), + ID = mo["SerialNumber"].ToString(), + Model = model, + SerialNumber = GetBiosSerialNumber(), + Guid = guid, + UUID = uuid + }; + } + + return new BiosInfo(); + }); + } + + #endregion 主板相关 + + #region 公共函数 + + /// + /// 将速度值格式化成字节单位 + /// + /// + /// + public static string FormatBytes(this double bytes) + { + int unit = 0; + while (bytes > 1024) + { + bytes /= 1024; + ++unit; + } + + string s = CompactFormat ? ((int)bytes).ToString() : bytes.ToString("F") + " "; + return s + (Unit)unit; + } + + private static float GetCounterValue(PerformanceCounter pc, string categoryName, string counterName, string instanceName) + { + if (!IsWinPlatform) return 0; + + pc.CategoryName = categoryName; + pc.CounterName = counterName; + pc.InstanceName = instanceName; + return pc.NextValue(); + } + + #endregion 公共函数 + + #region Win32API声明 #pragma warning disable 1591 - [DllImport("User32")] - public static extern int GetWindow(int hWnd, int wCmd); + [DllImport("User32")] + public static extern int GetWindow(int hWnd, int wCmd); - [DllImport("User32")] - public static extern int GetWindowLongA(int hWnd, int wIndx); + [DllImport("User32")] + public static extern int GetWindowLongA(int hWnd, int wIndx); - [DllImport("user32.dll")] - public static extern bool GetWindowText(int hWnd, StringBuilder title, int maxBufSize); + [DllImport("user32.dll")] + public static extern bool GetWindowText(int hWnd, StringBuilder title, int maxBufSize); - [DllImport("user32", CharSet = CharSet.Auto)] - public static extern int GetWindowTextLength(IntPtr hWnd); + [DllImport("user32", CharSet = CharSet.Auto)] + public static extern int GetWindowTextLength(IntPtr hWnd); #pragma warning restore 1591 - #endregion Win32API声明 - } + #endregion Win32API声明 + } } \ No newline at end of file diff --git a/Masuit.Tools.Abstractions/Masuit.Tools.Abstractions.csproj b/Masuit.Tools.Abstractions/Masuit.Tools.Abstractions.csproj index 96d24f6c..b1ca3217 100644 --- a/Masuit.Tools.Abstractions/Masuit.Tools.Abstractions.csproj +++ b/Masuit.Tools.Abstractions/Masuit.Tools.Abstractions.csproj @@ -51,7 +51,7 @@ - + @@ -102,7 +102,7 @@ - + diff --git a/Masuit.Tools.AspNetCore/Masuit.Tools.AspNetCore.csproj b/Masuit.Tools.AspNetCore/Masuit.Tools.AspNetCore.csproj index 7958256b..81747274 100644 --- a/Masuit.Tools.AspNetCore/Masuit.Tools.AspNetCore.csproj +++ b/Masuit.Tools.AspNetCore/Masuit.Tools.AspNetCore.csproj @@ -44,7 +44,7 @@ - + @@ -64,6 +64,6 @@ - + \ No newline at end of file diff --git a/Masuit.Tools.Core/Masuit.Tools.Core.csproj b/Masuit.Tools.Core/Masuit.Tools.Core.csproj index dbbd2c6f..906d7fcf 100644 --- a/Masuit.Tools.Core/Masuit.Tools.Core.csproj +++ b/Masuit.Tools.Core/Masuit.Tools.Core.csproj @@ -54,7 +54,7 @@ github:https://github.com/ldqk/Masuit.Tools - + diff --git a/Masuit.Tools.Excel/Masuit.Tools.Excel.csproj b/Masuit.Tools.Excel/Masuit.Tools.Excel.csproj index fa14fc5d..72fae904 100644 --- a/Masuit.Tools.Excel/Masuit.Tools.Excel.csproj +++ b/Masuit.Tools.Excel/Masuit.Tools.Excel.csproj @@ -37,7 +37,7 @@ - + diff --git a/NetCoreTest/NetCoreTest.csproj b/NetCoreTest/NetCoreTest.csproj index 34824319..79cccf22 100644 --- a/NetCoreTest/NetCoreTest.csproj +++ b/NetCoreTest/NetCoreTest.csproj @@ -6,7 +6,7 @@ false - + diff --git a/Test/Masuit.Tools.Abstractions.Test/Masuit.Tools.Abstractions.Test.csproj b/Test/Masuit.Tools.Abstractions.Test/Masuit.Tools.Abstractions.Test.csproj index d867ac85..b9ebc686 100644 --- a/Test/Masuit.Tools.Abstractions.Test/Masuit.Tools.Abstractions.Test.csproj +++ b/Test/Masuit.Tools.Abstractions.Test/Masuit.Tools.Abstractions.Test.csproj @@ -14,7 +14,7 @@ - + all runtime; build; native; contentfiles; analyzers; buildtransitive diff --git a/Test/Masuit.Tools.AspNetCore.ResumeFileResults.WebTest/Masuit.Tools.AspNetCore.ResumeFileResults.WebTest.csproj b/Test/Masuit.Tools.AspNetCore.ResumeFileResults.WebTest/Masuit.Tools.AspNetCore.ResumeFileResults.WebTest.csproj index 08b3511c..e41aff8c 100644 --- a/Test/Masuit.Tools.AspNetCore.ResumeFileResults.WebTest/Masuit.Tools.AspNetCore.ResumeFileResults.WebTest.csproj +++ b/Test/Masuit.Tools.AspNetCore.ResumeFileResults.WebTest/Masuit.Tools.AspNetCore.ResumeFileResults.WebTest.csproj @@ -23,7 +23,7 @@ - + diff --git a/Test/Masuit.Tools.Core.Test/Masuit.Tools.Core.Test.csproj b/Test/Masuit.Tools.Core.Test/Masuit.Tools.Core.Test.csproj index 8b1f103b..8e50061d 100644 --- a/Test/Masuit.Tools.Core.Test/Masuit.Tools.Core.Test.csproj +++ b/Test/Masuit.Tools.Core.Test/Masuit.Tools.Core.Test.csproj @@ -12,7 +12,7 @@ - + all runtime; build; native; contentfiles; analyzers diff --git a/Test/Masuit.Tools.Test/Masuit.Tools.Test.csproj b/Test/Masuit.Tools.Test/Masuit.Tools.Test.csproj index 0281c1be..ea355f3e 100644 --- a/Test/Masuit.Tools.Test/Masuit.Tools.Test.csproj +++ b/Test/Masuit.Tools.Test/Masuit.Tools.Test.csproj @@ -103,7 +103,7 @@ 4.5.0 - 2.9.1 + 2.9.2 2.0.3 @@ -114,16 +114,16 @@ all - 2.9.1 + 2.9.2 - 2.9.1 + 2.9.2 - 2.9.1 + 2.9.2 - 2.9.1 + 2.9.2