SystemInfo.cs 29 KB

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