SystemInfo.cs 26 KB

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