SystemInfo.cs 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882
  1. using Masuit.Tools.Logging;
  2. using Microsoft.Win32;
  3. using System;
  4. using System.Collections;
  5. using System.Collections.Generic;
  6. using System.Diagnostics;
  7. using System.Management;
  8. using System.Net;
  9. using System.Net.Sockets;
  10. using System.Runtime.InteropServices;
  11. using System.Text;
  12. using System.Text.RegularExpressions;
  13. using System.Threading;
  14. namespace Masuit.Tools.Hardware
  15. {
  16. /// <summary>
  17. /// 硬件信息,部分功能需要C++支持
  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. #endregion
  36. #region 构造函数
  37. /// <summary>
  38. /// 静态构造函数
  39. /// </summary>
  40. static SystemInfo()
  41. {
  42. //初始化CPU计数器
  43. PcCpuLoad = new PerformanceCounter("Processor", "% Processor Time", "_Total")
  44. {
  45. MachineName = "."
  46. };
  47. PcCpuLoad.NextValue();
  48. //CPU个数
  49. ProcessorCount = Environment.ProcessorCount;
  50. //获得物理内存
  51. try
  52. {
  53. ManagementClass mc = new ManagementClass("Win32_ComputerSystem");
  54. ManagementObjectCollection moc = mc.GetInstances();
  55. foreach (ManagementBaseObject mo in moc)
  56. {
  57. if (mo["TotalPhysicalMemory"] != null)
  58. {
  59. PhysicalMemory = long.Parse(mo["TotalPhysicalMemory"].ToString());
  60. }
  61. }
  62. PerformanceCounterCategory cat = new PerformanceCounterCategory("Network Interface");
  63. InstanceNames = cat.GetInstanceNames();
  64. NetRecvCounters = new PerformanceCounter[InstanceNames.Length];
  65. NetSentCounters = new PerformanceCounter[InstanceNames.Length];
  66. for (int i = 0; i < InstanceNames.Length; i++)
  67. {
  68. NetRecvCounters[i] = new PerformanceCounter();
  69. NetSentCounters[i] = new PerformanceCounter();
  70. }
  71. CompactFormat = false;
  72. }
  73. catch (Exception e)
  74. {
  75. LogManager.Error(e);
  76. }
  77. }
  78. #endregion
  79. private static bool CompactFormat { get; set; }
  80. #region CPU核心
  81. /// <summary>
  82. /// 获取CPU核心数
  83. /// </summary>
  84. public static int ProcessorCount { get; }
  85. #endregion
  86. #region CPU占用率
  87. /// <summary>
  88. /// 获取CPU占用率 %
  89. /// </summary>
  90. public static float CpuLoad => PcCpuLoad.NextValue();
  91. #endregion
  92. #region 可用内存
  93. /// <summary>
  94. /// 获取可用内存
  95. /// </summary>
  96. public static long MemoryAvailable
  97. {
  98. get
  99. {
  100. try
  101. {
  102. long availablebytes = 0;
  103. ManagementClass mos = new ManagementClass("Win32_OperatingSystem");
  104. foreach (var o in mos.GetInstances())
  105. {
  106. var mo = (ManagementObject)o;
  107. if (mo["FreePhysicalMemory"] != null)
  108. {
  109. availablebytes = 1024 * long.Parse(mo["FreePhysicalMemory"].ToString());
  110. }
  111. }
  112. return availablebytes;
  113. }
  114. catch (Exception)
  115. {
  116. return 0;
  117. }
  118. }
  119. }
  120. #endregion
  121. #region 物理内存
  122. /// <summary>
  123. /// 获取物理内存
  124. /// </summary>
  125. public static long PhysicalMemory { get; }
  126. #endregion
  127. #region 查找所有应用程序标题
  128. /// <summary>
  129. /// 查找所有应用程序标题
  130. /// </summary>
  131. /// <param name="handle">应用程序标题范型</param>
  132. /// <returns>所有应用程序集合</returns>
  133. public static ArrayList FindAllApps(int handle)
  134. {
  135. ArrayList apps = new ArrayList();
  136. int hwCurr = GetWindow(handle, GwHwndfirst);
  137. while (hwCurr > 0)
  138. {
  139. int IsTask = WsVisible | WsBorder;
  140. int lngStyle = GetWindowLongA(hwCurr, GwlStyle);
  141. bool taskWindow = (lngStyle & IsTask) == IsTask;
  142. if (taskWindow)
  143. {
  144. int length = GetWindowTextLength(new IntPtr(hwCurr));
  145. StringBuilder sb = new StringBuilder(2 * length + 1);
  146. GetWindowText(hwCurr, sb, sb.Capacity);
  147. string strTitle = sb.ToString();
  148. if (!string.IsNullOrEmpty(strTitle))
  149. {
  150. apps.Add(strTitle);
  151. }
  152. }
  153. hwCurr = GetWindow(hwCurr, GwHwndnext);
  154. }
  155. return apps;
  156. }
  157. #endregion
  158. #region 获取CPU的数量
  159. /// <summary>
  160. /// 获取CPU的数量
  161. /// </summary>
  162. /// <returns>CPU的数量</returns>
  163. public static int GetCpuCount()
  164. {
  165. try
  166. {
  167. ManagementClass m = new ManagementClass("Win32_Processor");
  168. ManagementObjectCollection mn = m.GetInstances();
  169. return mn.Count;
  170. }
  171. catch (Exception)
  172. {
  173. return 0;
  174. }
  175. }
  176. #endregion
  177. #region 获取CPU信息
  178. /// <summary>
  179. /// 获取CPU信息
  180. /// </summary>
  181. /// <returns>CPU信息</returns>
  182. public static List<CpuInfo> GetCpuInfo()
  183. {
  184. try
  185. {
  186. List<CpuInfo> list = new List<CpuInfo>();
  187. ManagementObjectSearcher mySearcher = new ManagementObjectSearcher("SELECT * FROM Win32_Processor");
  188. foreach (var o in mySearcher.Get())
  189. {
  190. var myObject = (ManagementObject)o;
  191. list.Add(new CpuInfo
  192. {
  193. CpuLoad = CpuLoad,
  194. NumberOfLogicalProcessors = ProcessorCount,
  195. CurrentClockSpeed = myObject.Properties["CurrentClockSpeed"].Value.ToString(),
  196. Manufacturer = myObject.Properties["Manufacturer"].Value.ToString(),
  197. MaxClockSpeed = myObject.Properties["MaxClockSpeed"].Value.ToString(),
  198. Type = myObject.Properties["Name"].Value.ToString(),
  199. DataWidth = myObject.Properties["DataWidth"].Value.ToString(),
  200. DeviceID = myObject.Properties["DeviceID"].Value.ToString(),
  201. NumberOfCores = Convert.ToInt32(myObject.Properties["NumberOfCores"].Value),
  202. Temperature = GetCPUTemperature()
  203. });
  204. }
  205. return list;
  206. }
  207. catch (Exception)
  208. {
  209. return new List<CpuInfo>();
  210. }
  211. }
  212. #endregion
  213. #region 获取内存信息
  214. /// <summary>
  215. /// 获取内存信息
  216. /// </summary>
  217. /// <returns>内存信息</returns>
  218. public static RamInfo GetRamInfo()
  219. {
  220. var info = new RamInfo();
  221. info.MemoryAvailable = GetFreePhysicalMemory();
  222. info.PhysicalMemory = GetTotalPhysicalMemory();
  223. info.TotalPageFile = GetTotalVirtualMemory();
  224. info.AvailablePageFile = GetTotalVirtualMemory() - GetUsedVirtualMemory();
  225. info.AvailableVirtual = 1 - GetUsageVirtualMemory();
  226. info.TotalVirtual = 1 - GetUsedPhysicalMemory();
  227. return info;
  228. }
  229. #endregion
  230. #region 获取CPU温度
  231. /// <summary>
  232. /// 获取CPU温度
  233. /// </summary>
  234. /// <returns>CPU温度</returns>
  235. public static double GetCPUTemperature()
  236. {
  237. try
  238. {
  239. string str = "";
  240. ManagementObjectSearcher vManagementObjectSearcher = new ManagementObjectSearcher(@"root\WMI", @"select * from MSAcpi_ThermalZoneTemperature");
  241. foreach (ManagementObject managementObject in vManagementObjectSearcher.Get())
  242. {
  243. str += managementObject.Properties["CurrentTemperature"].Value.ToString();
  244. }
  245. //这就是CPU的温度了
  246. double temp = (double.Parse(str) - 2732) / 10;
  247. return Math.Round(temp, 2);
  248. }
  249. catch (Exception)
  250. {
  251. return 0;
  252. }
  253. }
  254. #endregion
  255. #region WMI接口获取CPU使用率
  256. /// <summary>
  257. /// WMI接口获取CPU使用率
  258. /// </summary>
  259. /// <returns></returns>
  260. public static string GetProcessorData()
  261. {
  262. double d = GetCounterValue(CpuCounter, "Processor", "% Processor Time", "_Total");
  263. return CompactFormat ? (int)d + "%" : d.ToString("F") + "%";
  264. }
  265. #endregion
  266. #region 获取虚拟内存使用率详情
  267. /// <summary>
  268. /// 获取虚拟内存使用率详情
  269. /// </summary>
  270. /// <returns></returns>
  271. public static string GetMemoryVData()
  272. {
  273. double d = GetCounterValue(MemoryCounter, "Memory", "% Committed Bytes In Use", null);
  274. var str = d.ToString("F") + "% (";
  275. d = GetCounterValue(MemoryCounter, "Memory", "Committed Bytes", null);
  276. str += FormatBytes(d) + " / ";
  277. d = GetCounterValue(MemoryCounter, "Memory", "Commit Limit", null);
  278. return str + FormatBytes(d) + ") ";
  279. }
  280. /// <summary>
  281. /// 获取虚拟内存使用率
  282. /// </summary>
  283. /// <returns></returns>
  284. public static double GetUsageVirtualMemory()
  285. {
  286. return GetCounterValue(MemoryCounter, "Memory", "% Committed Bytes In Use", null);
  287. }
  288. /// <summary>
  289. /// 获取虚拟内存已用大小
  290. /// </summary>
  291. /// <returns></returns>
  292. public static double GetUsedVirtualMemory()
  293. {
  294. return GetCounterValue(MemoryCounter, "Memory", "Committed Bytes", null);
  295. }
  296. /// <summary>
  297. /// 获取虚拟内存总大小
  298. /// </summary>
  299. /// <returns></returns>
  300. public static double GetTotalVirtualMemory()
  301. {
  302. return GetCounterValue(MemoryCounter, "Memory", "Commit Limit", null);
  303. }
  304. #endregion
  305. #region 获取物理内存使用率详情
  306. /// <summary>
  307. /// 获取物理内存使用率详情描述
  308. /// </summary>
  309. /// <returns></returns>
  310. public static string GetMemoryPData()
  311. {
  312. string s = QueryComputerSystem("totalphysicalmemory");
  313. double totalphysicalmemory = Convert.ToDouble(s);
  314. double d = GetCounterValue(MemoryCounter, "Memory", "Available Bytes", null);
  315. d = totalphysicalmemory - d;
  316. s = CompactFormat ? "%" : "% (" + FormatBytes(d) + " / " + FormatBytes(totalphysicalmemory) + ")";
  317. d /= totalphysicalmemory;
  318. d *= 100;
  319. return CompactFormat ? (int)d + s : d.ToString("F") + s;
  320. }
  321. /// <summary>
  322. /// 获取物理内存总数,单位B
  323. /// </summary>
  324. /// <returns></returns>
  325. public static double GetTotalPhysicalMemory()
  326. {
  327. string s = QueryComputerSystem("totalphysicalmemory");
  328. return s.ToDouble();
  329. }
  330. /// <summary>
  331. /// 获取空闲的物理内存数,单位B
  332. /// </summary>
  333. /// <returns></returns>
  334. public static double GetFreePhysicalMemory()
  335. {
  336. return GetCounterValue(MemoryCounter, "Memory", "Available Bytes", null);
  337. }
  338. /// <summary>
  339. /// 获取已经使用了的物理内存数,单位B
  340. /// </summary>
  341. /// <returns></returns>
  342. public static double GetUsedPhysicalMemory()
  343. {
  344. return GetTotalPhysicalMemory() - GetFreePhysicalMemory();
  345. }
  346. #endregion
  347. #region 获取硬盘的读写速率
  348. /// <summary>
  349. /// 获取硬盘的读写速率
  350. /// </summary>
  351. /// <param name="dd">读或写</param>
  352. /// <returns></returns>
  353. public static double 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;
  354. #endregion
  355. #region 获取网络的传输速率
  356. /// <summary>
  357. /// 获取网络的传输速率
  358. /// </summary>
  359. /// <param name="nd">上传或下载</param>
  360. /// <returns></returns>
  361. public static double GetNetData(NetData nd)
  362. {
  363. if (InstanceNames.Length == 0)
  364. {
  365. return 0;
  366. }
  367. double d = 0;
  368. for (int i = 0; i < InstanceNames.Length; i++)
  369. {
  370. double receied = GetCounterValue(NetRecvCounters[i], "Network Interface", "Bytes Received/sec", InstanceNames[i]);
  371. double send = GetCounterValue(NetSentCounters[i], "Network Interface", "Bytes Sent/sec", InstanceNames[i]);
  372. switch (nd)
  373. {
  374. case NetData.Received:
  375. d += receied;
  376. break;
  377. case NetData.Sent:
  378. d += send;
  379. break;
  380. case NetData.ReceivedAndSent:
  381. d += receied + send;
  382. break;
  383. default:
  384. d += 0;
  385. break;
  386. }
  387. }
  388. return d;
  389. }
  390. #endregion
  391. /// <summary>
  392. /// 获取网卡硬件地址
  393. /// </summary>
  394. /// <returns></returns>
  395. public static IList<string> GetMacAddress()
  396. {
  397. //获取网卡硬件地址
  398. try
  399. {
  400. IList<string> list = new List<string>();
  401. using var mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
  402. using var moc = mc.GetInstances();
  403. foreach (ManagementObject mo in moc)
  404. {
  405. if ((bool)mo["IPEnabled"])
  406. {
  407. list.Add(mo["MacAddress"].ToString());
  408. }
  409. }
  410. return list;
  411. }
  412. catch (Exception)
  413. {
  414. return new List<string>();
  415. }
  416. }
  417. /// <summary>
  418. /// 获取IP地址
  419. /// </summary>
  420. /// <returns></returns>
  421. public static IList<string> GetIPAddress()
  422. {
  423. //获取IP地址
  424. try
  425. {
  426. IList<string> list = new List<string>();
  427. using var mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
  428. using var moc = mc.GetInstances();
  429. foreach (ManagementObject mo in moc)
  430. {
  431. if ((bool)mo["IPEnabled"])
  432. {
  433. var ar = (Array)(mo.Properties["IpAddress"].Value);
  434. var st = ar.GetValue(0).ToString();
  435. list.Add(st);
  436. }
  437. }
  438. return list;
  439. }
  440. catch (Exception)
  441. {
  442. return new List<string>()
  443. {
  444. "未能获取到当前计算机的IP地址,可能是当前程序无管理员权限,如果是web应用程序,请将应用程序池的高级设置中的进程模型下的标识设置为:LocalSystem;如果是普通桌面应用程序,请提升管理员权限后再操作。"
  445. };
  446. }
  447. }
  448. /// <summary>
  449. /// 获取当前使用的IP
  450. /// </summary>
  451. /// <returns></returns>
  452. public static string GetLocalUsedIP()
  453. {
  454. string result = RunApp("route", "print", true);
  455. var m = Regex.Match(result, @"0.0.0.0\s+0.0.0.0\s+(\d+.\d+.\d+.\d+)\s+(\d+.\d+.\d+.\d+)", RegexOptions.Compiled);
  456. if (m.Success)
  457. {
  458. return m.Groups[2].Value;
  459. }
  460. try
  461. {
  462. using var c = new TcpClient();
  463. c.Connect("www.baidu.com", 80);
  464. var ip = ((IPEndPoint)c.Client.LocalEndPoint).Address.ToString();
  465. return ip;
  466. }
  467. catch (Exception)
  468. {
  469. return "未能获取当前使用的IP,可能是当前程序无管理员权限,如果是web应用程序,请将应用程序池的高级设置中的进程模型下的标识设置为:LocalSystem;如果是普通桌面应用程序,请提升管理员权限后再操作。";
  470. }
  471. }
  472. /// <summary>
  473. /// 运行一个控制台程序并返回其输出参数。
  474. /// </summary>
  475. /// <param name="filename">程序名</param>
  476. /// <param name="arguments">输入参数</param>
  477. /// <param name="recordLog">是否记录日志</param>
  478. /// <returns></returns>
  479. public static string RunApp(string filename, string arguments, bool recordLog)
  480. {
  481. try
  482. {
  483. if (recordLog)
  484. {
  485. Trace.WriteLine(filename + " " + arguments);
  486. }
  487. Process proc = new Process
  488. {
  489. StartInfo =
  490. {
  491. FileName = filename,
  492. CreateNoWindow = true,
  493. Arguments = arguments,
  494. RedirectStandardOutput = true,
  495. UseShellExecute = false
  496. }
  497. };
  498. proc.Start();
  499. using var sr = new System.IO.StreamReader(proc.StandardOutput.BaseStream, Encoding.Default);
  500. Thread.Sleep(100); //貌似调用系统的nslookup还未返回数据或者数据未编码完成,程序就已经跳过直接执行
  501. //txt = sr.ReadToEnd()了,导致返回的数据为空,故睡眠令硬件反应
  502. if (!proc.HasExited) //在无参数调用nslookup后,可以继续输入命令继续操作,如果进程未停止就直接执行
  503. {
  504. //txt = sr.ReadToEnd()程序就在等待输入,而且又无法输入,直接掐住无法继续运行
  505. proc.Kill();
  506. }
  507. string txt = sr.ReadToEnd();
  508. sr.Close();
  509. if (recordLog)
  510. {
  511. Trace.WriteLine(txt);
  512. }
  513. return txt;
  514. }
  515. catch (Exception ex)
  516. {
  517. Trace.WriteLine(ex);
  518. return ex.Message;
  519. }
  520. }
  521. /// <summary>
  522. /// 获取操作系统版本
  523. /// </summary>
  524. /// <returns></returns>
  525. public static string GetOsVersion()
  526. {
  527. try
  528. {
  529. return Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion")?.GetValue("ProductName").ToString();
  530. }
  531. catch (Exception)
  532. {
  533. return "未能获取到操作系统版本,可能是当前程序无管理员权限,如果是web应用程序,请将应用程序池的高级设置中的进程模型下的标识设置为:LocalSystem;如果是普通桌面应用程序,请提升管理员权限后再操作。";
  534. }
  535. }
  536. #region 将速度值格式化成字节单位
  537. /// <summary>
  538. /// 将速度值格式化成字节单位
  539. /// </summary>
  540. /// <param name="bytes"></param>
  541. /// <returns></returns>
  542. public static string FormatBytes(this double bytes)
  543. {
  544. int unit = 0;
  545. while (bytes > 1024)
  546. {
  547. bytes /= 1024;
  548. ++unit;
  549. }
  550. string s = CompactFormat ? ((int)bytes).ToString() : bytes.ToString("F") + " ";
  551. return s + (Unit)unit;
  552. }
  553. #endregion
  554. #region 查询计算机系统信息
  555. /// <summary>
  556. /// 获取计算机开机时间
  557. /// </summary>
  558. /// <returns>datetime</returns>
  559. public static DateTime BootTime()
  560. {
  561. var query = new SelectQuery("SELECT LastBootUpTime FROM Win32_OperatingSystem WHERE Primary='true'");
  562. var searcher = new ManagementObjectSearcher(query);
  563. foreach (ManagementObject mo in searcher.Get())
  564. {
  565. return ManagementDateTimeConverter.ToDateTime(mo.Properties["LastBootUpTime"].Value.ToString());
  566. }
  567. return DateTime.Now - TimeSpan.FromMilliseconds(Environment.TickCount & Int32.MaxValue);
  568. }
  569. /// <summary>
  570. /// 查询计算机系统信息
  571. /// </summary>
  572. /// <param name="type">类型名</param>
  573. /// <returns></returns>
  574. public static string QueryComputerSystem(string type)
  575. {
  576. try
  577. {
  578. string str = null;
  579. ManagementObjectSearcher objCS = new ManagementObjectSearcher("SELECT * FROM Win32_ComputerSystem");
  580. foreach (ManagementObject objMgmt in objCS.Get())
  581. {
  582. str = objMgmt[type].ToString();
  583. }
  584. return str;
  585. }
  586. catch (Exception e)
  587. {
  588. return "未能获取到当前计算机系统信息,可能是当前程序无管理员权限,如果是web应用程序,请将应用程序池的高级设置中的进程模型下的标识设置为:LocalSystem;如果是普通桌面应用程序,请提升管理员权限后再操作。异常信息:" + e.Message;
  589. }
  590. }
  591. #endregion
  592. #region 获取环境变量
  593. /// <summary>
  594. /// 获取环境变量
  595. /// </summary>
  596. /// <param name="type">环境变量名</param>
  597. /// <returns></returns>
  598. public static string QueryEnvironment(string type) => Environment.ExpandEnvironmentVariables(type);
  599. #endregion
  600. #region 获取磁盘空间
  601. /// <summary>
  602. /// 获取磁盘可用空间
  603. /// </summary>
  604. /// <returns></returns>
  605. public static Dictionary<string, string> DiskFree()
  606. {
  607. try
  608. {
  609. Dictionary<string, string> dic = new Dictionary<string, string>();
  610. ManagementObjectSearcher objCS = new ManagementObjectSearcher("SELECT * FROM Win32_LogicalDisk");
  611. foreach (ManagementObject objMgmt in objCS.Get())
  612. {
  613. var device = objMgmt["DeviceID"];
  614. if (null != device)
  615. {
  616. var space = objMgmt["FreeSpace"];
  617. if (null != space)
  618. {
  619. dic.Add(device.ToString(), FormatBytes(double.Parse(space.ToString())));
  620. }
  621. }
  622. }
  623. return dic;
  624. }
  625. catch (Exception)
  626. {
  627. return new Dictionary<string, string>()
  628. {
  629. { "null", "未能获取到当前计算机的磁盘信息,可能是当前程序无管理员权限,如果是web应用程序,请将应用程序池的高级设置中的进程模型下的标识设置为:LocalSystem;如果是普通桌面应用程序,请提升管理员权限后再操作。" }
  630. };
  631. }
  632. }
  633. /// <summary>
  634. /// 获取磁盘总空间
  635. /// </summary>
  636. /// <returns></returns>
  637. public static Dictionary<string, string> DiskTotalSpace()
  638. {
  639. try
  640. {
  641. Dictionary<string, string> dic = new Dictionary<string, string>();
  642. ManagementObjectSearcher objCS = new ManagementObjectSearcher("SELECT * FROM Win32_LogicalDisk");
  643. foreach (ManagementObject objMgmt in objCS.Get())
  644. {
  645. var device = objMgmt["DeviceID"];
  646. if (null != device)
  647. {
  648. var space = objMgmt["Size"];
  649. if (null != space)
  650. {
  651. dic.Add(device.ToString(), FormatBytes(double.Parse(space.ToString())));
  652. }
  653. }
  654. }
  655. return dic;
  656. }
  657. catch (Exception)
  658. {
  659. return new Dictionary<string, string>();
  660. }
  661. }
  662. /// <summary>
  663. /// 获取磁盘已用空间
  664. /// </summary>
  665. /// <returns></returns>
  666. public static Dictionary<string, string> DiskUsedSpace()
  667. {
  668. try
  669. {
  670. Dictionary<string, string> dic = new Dictionary<string, string>();
  671. ManagementObjectSearcher objCS = new ManagementObjectSearcher("SELECT * FROM Win32_LogicalDisk");
  672. foreach (ManagementObject objMgmt in objCS.Get())
  673. {
  674. var device = objMgmt["DeviceID"];
  675. if (null != device)
  676. {
  677. var free = objMgmt["FreeSpace"];
  678. var total = objMgmt["Size"];
  679. if (null != total)
  680. {
  681. dic.Add(device.ToString(), FormatBytes(double.Parse(total.ToString()) - free.ToString().ToDouble()));
  682. }
  683. }
  684. }
  685. return dic;
  686. }
  687. catch (Exception)
  688. {
  689. return new Dictionary<string, string>()
  690. {
  691. { "null", "未能获取到当前计算机的磁盘信息,可能是当前程序无管理员权限,如果是web应用程序,请将应用程序池的高级设置中的进程模型下的标识设置为:LocalSystem;如果是普通桌面应用程序,请提升管理员权限后再操作。" }
  692. };
  693. }
  694. }
  695. /// <summary>
  696. /// 获取磁盘使用率
  697. /// </summary>
  698. /// <returns></returns>
  699. public static Dictionary<string, double> DiskUsage()
  700. {
  701. try
  702. {
  703. Dictionary<string, double> dic = new Dictionary<string, double>();
  704. ManagementObjectSearcher objCS = new ManagementObjectSearcher("SELECT * FROM Win32_LogicalDisk");
  705. foreach (ManagementObject objMgmt in objCS.Get())
  706. {
  707. var device = objMgmt["DeviceID"];
  708. if (null != device)
  709. {
  710. var free = objMgmt["FreeSpace"];
  711. var total = objMgmt["Size"];
  712. if (null != total && total.ToString().ToDouble() > 0)
  713. {
  714. dic.Add(device.ToString(), 1 - free.ToString().ToDouble() / total.ToString().ToDouble());
  715. }
  716. }
  717. }
  718. return dic;
  719. }
  720. catch (Exception)
  721. {
  722. return new Dictionary<string, double>()
  723. {
  724. { "未能获取到当前计算机的磁盘信息,可能是当前程序无管理员权限,如果是web应用程序,请将应用程序池的高级设置中的进程模型下的标识设置为:LocalSystem;如果是普通桌面应用程序,请提升管理员权限后再操作。", 0 }
  725. };
  726. }
  727. }
  728. #endregion
  729. private static double GetCounterValue(PerformanceCounter pc, string categoryName, string counterName, string instanceName)
  730. {
  731. pc.CategoryName = categoryName;
  732. pc.CounterName = counterName;
  733. pc.InstanceName = instanceName;
  734. return pc.NextValue();
  735. }
  736. #region Win32API声明
  737. #pragma warning disable 1591
  738. [DllImport("kernel32")]
  739. public static extern void GetWindowsDirectory(StringBuilder winDir, int count);
  740. [DllImport("kernel32")]
  741. public static extern void GetSystemDirectory(StringBuilder sysDir, int count);
  742. [DllImport("kernel32")]
  743. public static extern void GetSystemInfo(ref CPU_INFO cpuinfo);
  744. [DllImport("kernel32")]
  745. public static extern void GlobalMemoryStatus(ref MemoryInfo meminfo);
  746. [DllImport("kernel32")]
  747. public static extern void GetSystemTime(ref SystemtimeInfo stinfo);
  748. [DllImport("IpHlpApi.dll")]
  749. public static extern uint GetIfTable(byte[] pIfTable, ref uint pdwSize, bool bOrder);
  750. [DllImport("User32")]
  751. public static extern int GetWindow(int hWnd, int wCmd);
  752. [DllImport("User32")]
  753. public static extern int GetWindowLongA(int hWnd, int wIndx);
  754. [DllImport("user32.dll")]
  755. public static extern bool GetWindowText(int hWnd, StringBuilder title, int maxBufSize);
  756. [DllImport("user32", CharSet = CharSet.Auto)]
  757. public static extern int GetWindowTextLength(IntPtr hWnd);
  758. #pragma warning restore 1591
  759. #endregion
  760. }
  761. }