SystemInfo.cs 31 KB

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