SystemInfo.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693
  1. using Masuit.Tools.Logging;
  2. using System;
  3. using System.Collections;
  4. using System.Collections.Generic;
  5. using System.Diagnostics;
  6. using System.Linq;
  7. using System.Management;
  8. using System.Net;
  9. using System.Net.NetworkInformation;
  10. using System.Runtime.InteropServices;
  11. using System.Text;
  12. using System.Threading.Tasks;
  13. namespace Masuit.Tools.Hardware
  14. {
  15. /// <summary>
  16. /// 硬件信息,部分功能需要C++支持,仅支持Windows系统
  17. /// </summary>
  18. public static partial class SystemInfo
  19. {
  20. #region 字段
  21. private const int GwHwndfirst = 0;
  22. private const int GwHwndnext = 2;
  23. private const int GwlStyle = -16;
  24. private const int WsVisible = 268435456;
  25. private const int WsBorder = 8388608;
  26. private static readonly PerformanceCounter PcCpuLoad; //CPU计数器
  27. private static readonly PerformanceCounter MemoryCounter = new PerformanceCounter();
  28. private static readonly PerformanceCounter CpuCounter = new PerformanceCounter();
  29. private static readonly PerformanceCounter DiskReadCounter = new PerformanceCounter();
  30. private static readonly PerformanceCounter DiskWriteCounter = new PerformanceCounter();
  31. private static readonly string[] InstanceNames;
  32. private static readonly PerformanceCounter[] NetRecvCounters;
  33. private static readonly PerformanceCounter[] NetSentCounters;
  34. #endregion 字段
  35. #region 构造函数
  36. /// <summary>
  37. /// 静态构造函数
  38. /// </summary>
  39. static SystemInfo()
  40. {
  41. //初始化CPU计数器
  42. PcCpuLoad = new PerformanceCounter("Processor", "% Processor Time", "_Total")
  43. {
  44. MachineName = "."
  45. };
  46. PcCpuLoad.NextValue();
  47. //CPU个数
  48. ProcessorCount = Environment.ProcessorCount;
  49. //获得物理内存
  50. try
  51. {
  52. using var mc = new ManagementClass("Win32_ComputerSystem");
  53. using var moc = mc.GetInstances();
  54. foreach (var mo in moc)
  55. {
  56. using (mo)
  57. {
  58. if (mo["TotalPhysicalMemory"] != null)
  59. {
  60. PhysicalMemory = long.Parse(mo["TotalPhysicalMemory"].ToString());
  61. }
  62. }
  63. }
  64. var cat = new PerformanceCounterCategory("Network Interface");
  65. InstanceNames = cat.GetInstanceNames();
  66. NetRecvCounters = new PerformanceCounter[InstanceNames.Length];
  67. NetSentCounters = new PerformanceCounter[InstanceNames.Length];
  68. for (int i = 0; i < InstanceNames.Length; i++)
  69. {
  70. NetRecvCounters[i] = new PerformanceCounter();
  71. NetSentCounters[i] = new PerformanceCounter();
  72. }
  73. CompactFormat = false;
  74. }
  75. catch (Exception e)
  76. {
  77. LogManager.Error(e);
  78. }
  79. }
  80. #endregion 构造函数
  81. private static bool CompactFormat { get; set; }
  82. #region CPU核心
  83. /// <summary>
  84. /// 获取CPU核心数
  85. /// </summary>
  86. public static int ProcessorCount { get; }
  87. #endregion CPU核心
  88. #region CPU占用率
  89. /// <summary>
  90. /// 获取CPU占用率 %
  91. /// </summary>
  92. public static float CpuLoad => PcCpuLoad.NextValue();
  93. /// <summary>
  94. /// 获取当前进程的CPU使用率(至少需要0.5s)
  95. /// </summary>
  96. /// <returns></returns>
  97. public static async Task<double> GetCpuUsageForProcess()
  98. {
  99. var startTime = DateTime.UtcNow;
  100. using var p1 = Process.GetCurrentProcess();
  101. var startCpuUsage = p1.TotalProcessorTime;
  102. await Task.Delay(500);
  103. var endTime = DateTime.UtcNow;
  104. using var p2 = Process.GetCurrentProcess();
  105. var endCpuUsage = p2.TotalProcessorTime;
  106. var cpuUsedMs = (endCpuUsage - startCpuUsage).TotalMilliseconds;
  107. var totalMsPassed = (endTime - startTime).TotalMilliseconds;
  108. return cpuUsedMs / (Environment.ProcessorCount * totalMsPassed) * 100;
  109. }
  110. #endregion CPU占用率
  111. #region 可用内存
  112. /// <summary>
  113. /// 获取可用内存
  114. /// </summary>
  115. public static long MemoryAvailable
  116. {
  117. get
  118. {
  119. try
  120. {
  121. using var mc = new ManagementClass("Win32_OperatingSystem");
  122. using var moc = mc.GetInstances();
  123. foreach (var mo in moc)
  124. {
  125. using (mo)
  126. {
  127. if (mo["FreePhysicalMemory"] != null)
  128. {
  129. return 1024 * long.Parse(mo["FreePhysicalMemory"].ToString());
  130. }
  131. }
  132. }
  133. return 0;
  134. }
  135. catch (Exception)
  136. {
  137. return 0;
  138. }
  139. }
  140. }
  141. #endregion 可用内存
  142. #region 物理内存
  143. /// <summary>
  144. /// 获取物理内存
  145. /// </summary>
  146. public static long PhysicalMemory { get; }
  147. #endregion 物理内存
  148. #region 查找所有应用程序标题
  149. /// <summary>
  150. /// 查找所有应用程序标题
  151. /// </summary>
  152. /// <param name="handle">应用程序标题范型</param>
  153. /// <returns>所有应用程序集合</returns>
  154. public static ArrayList FindAllApps(int handle)
  155. {
  156. var apps = new ArrayList();
  157. int hwCurr = GetWindow(handle, GwHwndfirst);
  158. while (hwCurr > 0)
  159. {
  160. int IsTask = WsVisible | WsBorder;
  161. int lngStyle = GetWindowLongA(hwCurr, GwlStyle);
  162. bool taskWindow = (lngStyle & IsTask) == IsTask;
  163. if (taskWindow)
  164. {
  165. int length = GetWindowTextLength(new IntPtr(hwCurr));
  166. StringBuilder sb = new StringBuilder(2 * length + 1);
  167. GetWindowText(hwCurr, sb, sb.Capacity);
  168. string strTitle = sb.ToString();
  169. if (!string.IsNullOrEmpty(strTitle))
  170. {
  171. apps.Add(strTitle);
  172. }
  173. }
  174. hwCurr = GetWindow(hwCurr, GwHwndnext);
  175. }
  176. return apps;
  177. }
  178. #endregion 查找所有应用程序标题
  179. #region 获取CPU的数量
  180. /// <summary>
  181. /// 获取CPU的数量
  182. /// </summary>
  183. /// <returns>CPU的数量</returns>
  184. public static int GetCpuCount()
  185. {
  186. try
  187. {
  188. using var m = new ManagementClass("Win32_Processor");
  189. using var moc = m.GetInstances();
  190. return moc.Count;
  191. }
  192. catch (Exception)
  193. {
  194. return 0;
  195. }
  196. }
  197. #endregion 获取CPU的数量
  198. #region 获取CPU信息
  199. private static readonly Lazy<List<ManagementBaseObject>> CpuObjects = new Lazy<List<ManagementBaseObject>>(() =>
  200. {
  201. using var mos = new ManagementObjectSearcher("SELECT * FROM Win32_Processor");
  202. using var moc = mos.Get();
  203. return moc.AsParallel().Cast<ManagementBaseObject>().ToList();
  204. });
  205. /// <summary>
  206. /// 获取CPU信息
  207. /// </summary>
  208. /// <returns>CPU信息</returns>
  209. public static List<CpuInfo> GetCpuInfo()
  210. {
  211. try
  212. {
  213. return CpuObjects.Value.Select(mo => new CpuInfo
  214. {
  215. CpuLoad = CpuLoad,
  216. NumberOfLogicalProcessors = ProcessorCount,
  217. CurrentClockSpeed = mo.Properties["CurrentClockSpeed"].Value.ToString(),
  218. Manufacturer = mo.Properties["Manufacturer"].Value.ToString(),
  219. MaxClockSpeed = mo.Properties["MaxClockSpeed"].Value.ToString(),
  220. Type = mo.Properties["Name"].Value.ToString(),
  221. DataWidth = mo.Properties["DataWidth"].Value.ToString(),
  222. SerialNumber = mo.Properties["ProcessorId"].Value.ToString(),
  223. DeviceID = mo.Properties["DeviceID"].Value.ToString(),
  224. NumberOfCores = Convert.ToInt32(mo.Properties["NumberOfCores"].Value),
  225. Temperature = GetCPUTemperature()
  226. }).ToList();
  227. }
  228. catch (Exception)
  229. {
  230. return new List<CpuInfo>();
  231. }
  232. }
  233. #endregion 获取CPU信息
  234. #region 获取内存信息
  235. /// <summary>
  236. /// 获取内存信息
  237. /// </summary>
  238. /// <returns>内存信息</returns>
  239. public static RamInfo GetRamInfo()
  240. {
  241. return new RamInfo
  242. {
  243. MemoryAvailable = GetFreePhysicalMemory(),
  244. PhysicalMemory = GetTotalPhysicalMemory(),
  245. TotalPageFile = GetTotalVirtualMemory(),
  246. AvailablePageFile = GetTotalVirtualMemory() - GetUsedVirtualMemory(),
  247. AvailableVirtual = 1 - GetUsageVirtualMemory(),
  248. TotalVirtual = 1 - GetUsedPhysicalMemory()
  249. };
  250. }
  251. #endregion 获取内存信息
  252. #region 获取CPU温度
  253. /// <summary>
  254. /// 获取CPU温度
  255. /// </summary>
  256. /// <returns>CPU温度</returns>
  257. public static float GetCPUTemperature()
  258. {
  259. try
  260. {
  261. using var mos = new ManagementObjectSearcher(@"root\WMI", "select * from MSAcpi_ThermalZoneTemperature");
  262. using var moc = mos.Get();
  263. foreach (var mo in moc)
  264. {
  265. using (mo)
  266. {
  267. //这就是CPU的温度了
  268. var temp = (float.Parse(mo.Properties["CurrentTemperature"].Value.ToString()) - 2732) / 10;
  269. return (float)Math.Round(temp, 2);
  270. }
  271. }
  272. }
  273. catch (Exception)
  274. {
  275. return 0;
  276. }
  277. return 0;
  278. }
  279. #endregion 获取CPU温度
  280. #region WMI接口获取CPU使用率
  281. /// <summary>
  282. /// WMI接口获取CPU使用率
  283. /// </summary>
  284. /// <returns></returns>
  285. public static string GetProcessorData()
  286. {
  287. float d = GetCounterValue(CpuCounter, "Processor", "% Processor Time", "_Total");
  288. return CompactFormat ? (int)d + "%" : d.ToString("F") + "%";
  289. }
  290. #endregion WMI接口获取CPU使用率
  291. #region 获取虚拟内存使用率详情
  292. /// <summary>
  293. /// 获取虚拟内存使用率详情
  294. /// </summary>
  295. /// <returns></returns>
  296. public static string GetMemoryVData()
  297. {
  298. float d = GetCounterValue(MemoryCounter, "Memory", "% Committed Bytes In Use", null);
  299. var str = d.ToString("F") + "% (";
  300. d = GetCounterValue(MemoryCounter, "Memory", "Committed Bytes", null);
  301. str += FormatBytes(d) + " / ";
  302. d = GetCounterValue(MemoryCounter, "Memory", "Commit Limit", null);
  303. return str + FormatBytes(d) + ") ";
  304. }
  305. /// <summary>
  306. /// 获取虚拟内存使用率
  307. /// </summary>
  308. /// <returns></returns>
  309. public static float GetUsageVirtualMemory()
  310. {
  311. return GetCounterValue(MemoryCounter, "Memory", "% Committed Bytes In Use", null);
  312. }
  313. /// <summary>
  314. /// 获取虚拟内存已用大小
  315. /// </summary>
  316. /// <returns></returns>
  317. public static float GetUsedVirtualMemory()
  318. {
  319. return GetCounterValue(MemoryCounter, "Memory", "Committed Bytes", null);
  320. }
  321. /// <summary>
  322. /// 获取虚拟内存总大小
  323. /// </summary>
  324. /// <returns></returns>
  325. public static float GetTotalVirtualMemory()
  326. {
  327. return GetCounterValue(MemoryCounter, "Memory", "Commit Limit", null);
  328. }
  329. #endregion 获取虚拟内存使用率详情
  330. #region 获取物理内存使用率详情
  331. /// <summary>
  332. /// 获取物理内存使用率详情描述
  333. /// </summary>
  334. /// <returns></returns>
  335. public static string GetMemoryPData()
  336. {
  337. string s = QueryComputerSystem("totalphysicalmemory");
  338. float totalphysicalmemory = Convert.ToSingle(s);
  339. float d = GetCounterValue(MemoryCounter, "Memory", "Available Bytes", null);
  340. d = totalphysicalmemory - d;
  341. s = CompactFormat ? "%" : "% (" + FormatBytes(d) + " / " + FormatBytes(totalphysicalmemory) + ")";
  342. d /= totalphysicalmemory;
  343. d *= 100;
  344. return CompactFormat ? (int)d + s : d.ToString("F") + s;
  345. }
  346. /// <summary>
  347. /// 获取物理内存总数,单位B
  348. /// </summary>
  349. /// <returns></returns>
  350. public static float GetTotalPhysicalMemory()
  351. {
  352. string s = QueryComputerSystem("totalphysicalmemory");
  353. return s.TryConvertTo<float>();
  354. }
  355. /// <summary>
  356. /// 获取空闲的物理内存数,单位B
  357. /// </summary>
  358. /// <returns></returns>
  359. public static float GetFreePhysicalMemory()
  360. {
  361. return GetCounterValue(MemoryCounter, "Memory", "Available Bytes", null);
  362. }
  363. /// <summary>
  364. /// 获取已经使用了的物理内存数,单位B
  365. /// </summary>
  366. /// <returns></returns>
  367. public static float GetUsedPhysicalMemory()
  368. {
  369. return GetTotalPhysicalMemory() - GetFreePhysicalMemory();
  370. }
  371. #endregion 获取物理内存使用率详情
  372. #region 获取硬盘的读写速率
  373. /// <summary>
  374. /// 获取硬盘的读写速率
  375. /// </summary>
  376. /// <param name="dd">读或写</param>
  377. /// <returns></returns>
  378. public static float GetDiskData(DiskData dd) => dd == DiskData.Read ? GetCounterValue(DiskReadCounter, "PhysicalDisk", "Disk Read Bytes/sec", "_Total") : dd == DiskData.Write ? GetCounterValue(DiskWriteCounter, "PhysicalDisk", "Disk Write Bytes/sec", "_Total") : dd == DiskData.ReadAndWrite ? GetCounterValue(DiskReadCounter, "PhysicalDisk", "Disk Read Bytes/sec", "_Total") + GetCounterValue(DiskWriteCounter, "PhysicalDisk", "Disk Write Bytes/sec", "_Total") : 0;
  379. #endregion 获取硬盘的读写速率
  380. #region 获取网络的传输速率
  381. /// <summary>
  382. /// 获取网络的传输速率
  383. /// </summary>
  384. /// <param name="nd">上传或下载</param>
  385. /// <returns></returns>
  386. public static float GetNetData(NetData nd)
  387. {
  388. if (InstanceNames.Length == 0)
  389. {
  390. return 0;
  391. }
  392. float d = 0;
  393. for (int i = 0; i < InstanceNames.Length; i++)
  394. {
  395. float receied = GetCounterValue(NetRecvCounters[i], "Network Interface", "Bytes Received/sec", InstanceNames[i]);
  396. float send = GetCounterValue(NetSentCounters[i], "Network Interface", "Bytes Sent/sec", InstanceNames[i]);
  397. switch (nd)
  398. {
  399. case NetData.Received:
  400. d += receied;
  401. break;
  402. case NetData.Sent:
  403. d += send;
  404. break;
  405. case NetData.ReceivedAndSent:
  406. d += receied + send;
  407. break;
  408. default:
  409. d += 0;
  410. break;
  411. }
  412. }
  413. return d;
  414. }
  415. #endregion 获取网络的传输速率
  416. /// <summary>
  417. /// 获取网卡硬件地址
  418. /// </summary>
  419. /// <returns></returns>
  420. public static IList<string> GetMacAddress()
  421. {
  422. //获取网卡硬件地址
  423. try
  424. {
  425. IList<string> list = new List<string>();
  426. using var mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
  427. using var moc = mc.GetInstances();
  428. foreach (var mo in moc)
  429. {
  430. using (mo)
  431. {
  432. if ((bool)mo["IPEnabled"])
  433. {
  434. list.Add(mo["MacAddress"].ToString());
  435. }
  436. }
  437. }
  438. return list;
  439. }
  440. catch (Exception)
  441. {
  442. return new List<string>();
  443. }
  444. }
  445. /// <summary>
  446. /// 获取当前使用的IP
  447. /// </summary>
  448. /// <returns></returns>
  449. public static IPAddress GetLocalUsedIP()
  450. {
  451. return NetworkInterface.GetAllNetworkInterfaces().OrderByDescending(c => c.Speed).Where(c => c.NetworkInterfaceType != NetworkInterfaceType.Loopback && c.OperationalStatus == OperationalStatus.Up).SelectMany(n => n.GetIPProperties().UnicastAddresses.Select(u => u.Address)).FirstOrDefault();
  452. }
  453. /// <summary>
  454. /// 获取本机所有的ip地址
  455. /// </summary>
  456. /// <returns></returns>
  457. public static List<UnicastIPAddressInformation> GetLocalIPs()
  458. {
  459. var interfaces = NetworkInterface.GetAllNetworkInterfaces().OrderByDescending(c => c.Speed).Where(c => c.NetworkInterfaceType != NetworkInterfaceType.Loopback && c.OperationalStatus == OperationalStatus.Up); //所有网卡信息
  460. return interfaces.SelectMany(n => n.GetIPProperties().UnicastAddresses).ToList();
  461. }
  462. #region 将速度值格式化成字节单位
  463. /// <summary>
  464. /// 将速度值格式化成字节单位
  465. /// </summary>
  466. /// <param name="bytes"></param>
  467. /// <returns></returns>
  468. public static string FormatBytes(this double bytes)
  469. {
  470. int unit = 0;
  471. while (bytes > 1024)
  472. {
  473. bytes /= 1024;
  474. ++unit;
  475. }
  476. string s = CompactFormat ? ((int)bytes).ToString() : bytes.ToString("F") + " ";
  477. return s + (Unit)unit;
  478. }
  479. #endregion 将速度值格式化成字节单位
  480. #region 查询计算机系统信息
  481. /// <summary>
  482. /// 获取计算机开机时间
  483. /// </summary>
  484. /// <returns>datetime</returns>
  485. public static DateTime BootTime()
  486. {
  487. var query = new SelectQuery("SELECT LastBootUpTime FROM Win32_OperatingSystem WHERE Primary='true'");
  488. using var searcher = new ManagementObjectSearcher(query);
  489. using var moc = searcher.Get();
  490. foreach (var mo in moc)
  491. {
  492. using (mo)
  493. {
  494. return ManagementDateTimeConverter.ToDateTime(mo.Properties["LastBootUpTime"].Value.ToString());
  495. }
  496. }
  497. return DateTime.Now - TimeSpan.FromMilliseconds(Environment.TickCount & int.MaxValue);
  498. }
  499. /// <summary>
  500. /// 查询计算机系统信息
  501. /// </summary>
  502. /// <param name="type">类型名</param>
  503. /// <returns></returns>
  504. public static string QueryComputerSystem(string type)
  505. {
  506. try
  507. {
  508. var mos = new ManagementObjectSearcher("SELECT * FROM Win32_ComputerSystem");
  509. using var moc = mos.Get();
  510. foreach (var mo in moc)
  511. {
  512. using (mo)
  513. {
  514. return mo[type].ToString();
  515. }
  516. }
  517. }
  518. catch (Exception e)
  519. {
  520. return "未能获取到当前计算机系统信息,可能是当前程序无管理员权限,如果是web应用程序,请将应用程序池的高级设置中的进程模型下的标识设置为:LocalSystem;如果是普通桌面应用程序,请提升管理员权限后再操作。异常信息:" + e.Message;
  521. }
  522. return string.Empty;
  523. }
  524. #endregion 查询计算机系统信息
  525. #region 获取环境变量
  526. /// <summary>
  527. /// 获取环境变量
  528. /// </summary>
  529. /// <param name="type">环境变量名</param>
  530. /// <returns></returns>
  531. public static string QueryEnvironment(string type) => Environment.ExpandEnvironmentVariables(type);
  532. #endregion 获取环境变量
  533. #region 获取磁盘空间
  534. private static readonly List<DiskInfo> DiskInfos = new();
  535. /// <summary>
  536. /// 获取磁盘可用空间
  537. /// </summary>
  538. /// <returns></returns>
  539. public static List<DiskInfo> GetDiskInfo()
  540. {
  541. try
  542. {
  543. if (DiskInfos.Count > 0)
  544. {
  545. return DiskInfos;
  546. }
  547. using var mc = new ManagementClass("Win32_DiskDrive");
  548. using var moc = mc.GetInstances();
  549. foreach (var mo in moc)
  550. {
  551. using (mo)
  552. {
  553. DiskInfos.Add(new DiskInfo()
  554. {
  555. Total = float.Parse(mo["Size"].ToString()),
  556. Model = mo["Model"].ToString(),
  557. SerialNumber = mo["SerialNumber"].ToString(),
  558. });
  559. }
  560. }
  561. return DiskInfos;
  562. }
  563. catch (Exception)
  564. {
  565. return new List<DiskInfo>();
  566. }
  567. }
  568. #endregion 获取磁盘空间
  569. private static float GetCounterValue(PerformanceCounter pc, string categoryName, string counterName, string instanceName)
  570. {
  571. pc.CategoryName = categoryName;
  572. pc.CounterName = counterName;
  573. pc.InstanceName = instanceName;
  574. return pc.NextValue();
  575. }
  576. #region Win32API声明
  577. #pragma warning disable 1591
  578. [DllImport("User32")]
  579. public static extern int GetWindow(int hWnd, int wCmd);
  580. [DllImport("User32")]
  581. public static extern int GetWindowLongA(int hWnd, int wIndx);
  582. [DllImport("user32.dll")]
  583. public static extern bool GetWindowText(int hWnd, StringBuilder title, int maxBufSize);
  584. [DllImport("user32", CharSet = CharSet.Auto)]
  585. public static extern int GetWindowTextLength(IntPtr hWnd);
  586. #pragma warning restore 1591
  587. #endregion Win32API声明
  588. }
  589. }