Computer.cs 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  1. using Microsoft.IdentityModel.Logging;
  2. using System;
  3. using System.CodeDom.Compiler;
  4. using System.Collections.Generic;
  5. using System.Linq;
  6. using System.Runtime.InteropServices;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9. namespace EasyTemplate.Tool;
  10. public class Computer
  11. {
  12. public static ComputerInfo GetComputerInfo()
  13. {
  14. ComputerInfo computerInfo = new ComputerInfo();
  15. try
  16. {
  17. MemoryMetricsClient client = new MemoryMetricsClient();
  18. MemoryMetrics memoryMetrics = client.GetMetrics();
  19. computerInfo.RAMUsage = Math.Ceiling(memoryMetrics.Used / 1024).ToString() + " GB / " + Math.Ceiling(memoryMetrics.Total / 1024).ToString() + " GB";
  20. var rate = Math.Ceiling(100 * memoryMetrics.Used / memoryMetrics.Total);
  21. computerInfo.RAMUsageRate = rate.ToString() + "%";
  22. switch (rate)
  23. {
  24. default: computerInfo.RAMStatus = ComputerStatus.Normal; break;
  25. case >= 85: computerInfo.RAMStatus = ComputerStatus.Error; break;
  26. case >= 75 and < 90: computerInfo.RAMStatus = ComputerStatus.Warning; break;
  27. }
  28. computerInfo.CPURate = Math.Ceiling(GetCPURate().ToDouble()).ToString();
  29. computerInfo.RunTime = GetRunTime();
  30. }
  31. catch (Exception ex)
  32. {
  33. Log.Error(ex);
  34. }
  35. try
  36. {
  37. // 获取系统盘(通常是C盘)
  38. var systemDrive = new DriveInfo("C");
  39. if (systemDrive.IsReady)
  40. {
  41. // 总空间(字节)
  42. long totalSpace = systemDrive.TotalSize;
  43. // 可用空间(字节)
  44. long freeSpace = systemDrive.AvailableFreeSpace;
  45. // 已用空间(字节)
  46. long usedSpace = totalSpace - freeSpace;
  47. // 转换为GB
  48. double totalSpaceGB = Math.Round(totalSpace / 1024.0 / 1024 / 1024, 2);
  49. double freeSpaceGB = Math.Round(freeSpace / 1024.0 / 1024 / 1024, 2);
  50. double usedSpaceGB = Math.Round(usedSpace / 1024.0 / 1024 / 1024, 2);
  51. // 使用率
  52. double usagePercentage = Math.Round((double)usedSpace / totalSpace * 100, 2);
  53. switch (usagePercentage)
  54. {
  55. default: computerInfo.SystemDiskStatus = ComputerStatus.Normal; break;
  56. case >= 85: computerInfo.SystemDiskStatus = ComputerStatus.Error; break;
  57. case >= 75 and < 90: computerInfo.SystemDiskStatus = ComputerStatus.Warning; break;
  58. }
  59. computerInfo.SystemDiskUsage = $"{usedSpaceGB} GB / {totalSpaceGB} GB";
  60. computerInfo.SystemDiskUsageRate = $"{usagePercentage}%";
  61. }
  62. }
  63. catch (Exception ex)
  64. {
  65. }
  66. return computerInfo;
  67. }
  68. public static bool IsUnix()
  69. {
  70. var isUnix = RuntimeInformation.IsOSPlatform(OSPlatform.OSX) || RuntimeInformation.IsOSPlatform(OSPlatform.Linux);
  71. return isUnix;
  72. }
  73. public static string GetCPURate()
  74. {
  75. string cpuRate = string.Empty;
  76. if (IsUnix())
  77. {
  78. string output = ShellCmd.Bash("top -b -n1 | grep \"Cpu(s)\" | awk '{print $2 + $4}'");
  79. cpuRate = output.Trim();
  80. }
  81. else
  82. {
  83. string output = ShellCmd.Cmd("wmic", "cpu get LoadPercentage");
  84. cpuRate = output.Replace("LoadPercentage", string.Empty).Trim();
  85. }
  86. return cpuRate;
  87. }
  88. public static string GetRunTime()
  89. {
  90. string runTime = string.Empty;
  91. try
  92. {
  93. if (IsUnix())
  94. {
  95. string output = ShellCmd.Bash("uptime -s");
  96. output = output.Trim();
  97. runTime = Extension.FormatTime((DateTime.Now - output.ToDate()).TotalMilliseconds.ToString().Split('.')[0].ToLong());
  98. }
  99. else
  100. {
  101. string output = ShellCmd.Cmd("wmic", "OS get LastBootUpTime/Value");
  102. string[] outputArr = output.Split("=", StringSplitOptions.RemoveEmptyEntries);
  103. if (outputArr.Length == 2)
  104. {
  105. runTime = Extension.FormatTime((DateTime.Now - outputArr[1].Split('.')[0].ToDate()).TotalMilliseconds.ToString().Split('.')[0].ToLong());
  106. }
  107. }
  108. }
  109. catch (Exception ex)
  110. {
  111. Log.Error(ex);
  112. }
  113. return runTime;
  114. }
  115. }
  116. public class MemoryMetricsClient
  117. {
  118. public MemoryMetrics GetMetrics()
  119. {
  120. if (Computer.IsUnix())
  121. {
  122. return GetUnixMetrics();
  123. }
  124. return GetWindowsMetrics();
  125. }
  126. private MemoryMetrics GetWindowsMetrics()
  127. {
  128. string output = ShellCmd.Cmd("wmic", "OS get FreePhysicalMemory,TotalVisibleMemorySize /Value");
  129. var lines = output.Trim().Split("\n");
  130. var freeMemoryParts = lines[0].Split("=", StringSplitOptions.RemoveEmptyEntries);
  131. var totalMemoryParts = lines[1].Split("=", StringSplitOptions.RemoveEmptyEntries);
  132. var metrics = new MemoryMetrics();
  133. metrics.Total = Math.Round(double.Parse(totalMemoryParts[1]) / 1024, 0);
  134. metrics.Free = Math.Round(double.Parse(freeMemoryParts[1]) / 1024, 0);
  135. metrics.Used = metrics.Total - metrics.Free;
  136. return metrics;
  137. }
  138. private MemoryMetrics GetUnixMetrics()
  139. {
  140. string output = ShellCmd.Bash("free -m");
  141. var lines = output.Split("\n");
  142. var memory = lines[1].Split(" ", StringSplitOptions.RemoveEmptyEntries);
  143. var metrics = new MemoryMetrics();
  144. metrics.Total = double.Parse(memory[1]);
  145. metrics.Used = double.Parse(memory[2]);
  146. metrics.Free = double.Parse(memory[3]);
  147. return metrics;
  148. }
  149. }
  150. public class MemoryMetrics
  151. {
  152. public double Total { get; set; }
  153. public double Used { get; set; }
  154. public double Free { get; set; }
  155. }
  156. public enum ComputerStatus
  157. {
  158. Normal,
  159. Error,
  160. Warning
  161. }
  162. public class ComputerInfo
  163. {
  164. /// <summary>
  165. /// CPU使用率
  166. /// </summary>
  167. public string CPURate { get; set; }
  168. /// <summary>
  169. /// 总内存
  170. /// </summary>
  171. public string RAMUsage { get; set; }
  172. /// <summary>
  173. /// 内存使用率
  174. /// </summary>
  175. public string RAMUsageRate { get; set; }
  176. /// <summary>
  177. /// 内存状态
  178. /// </summary>
  179. public ComputerStatus RAMStatus { get; set; }
  180. /// <summary>
  181. /// 系统运行时间
  182. /// </summary>
  183. public string RunTime { get; set; }
  184. /// <summary>
  185. /// 系统盘用量
  186. /// </summary>
  187. public string SystemDiskUsage { get; set; }
  188. /// <summary>
  189. /// 系统盘使用率
  190. /// </summary>
  191. public string SystemDiskUsageRate { get; set; }
  192. /// <summary>
  193. /// 系统盘状态
  194. /// </summary>
  195. public ComputerStatus SystemDiskStatus { get; set; }
  196. }