计算机信息的帮助类

  1 public class ComputerHelper
  2 {
  3     /// <summary>
  4     /// 内存使用情况
  5     /// </summary>
  6     /// <returns></returns>
  7     public static MemoryMetrics GetComputerInfo()
  8     {
  9         try
 10         {
 11             MemoryMetricsClient client = new();
 12             MemoryMetrics memoryMetrics = IsUnix() ? client.GetUnixMetrics() : client.GetWindowsMetrics();
 13 
 14             memoryMetrics.FreeRam = Math.Round(memoryMetrics.Free / 1024, 2) + "GB";
 15             memoryMetrics.UsedRam = Math.Round(memoryMetrics.Used / 1024, 2) + "GB";
 16             memoryMetrics.TotalRAM = Math.Round(memoryMetrics.Total / 1024, 2) + "GB";
 17             memoryMetrics.RAMRate = Math.Ceiling(100 * memoryMetrics.Used / memoryMetrics.Total).ToString() + "%";
 18             memoryMetrics.CPURate = Math.Ceiling(GetCPURate().ParseToDouble()) + "%";
 19             return memoryMetrics;
 20         }
 21         catch (Exception ex)
 22         {
 23             Console.WriteLine("获取内存使用出错,msg=" + ex.Message + "," + ex.StackTrace);
 24         }
 25         return new MemoryMetrics();
 26     }
 27 
 28     /// <summary>
 29     /// 获取内存大小
 30     /// </summary>
 31     /// <returns></returns>
 32     public static List<DiskInfo> GetDiskInfos()
 33     {
 34         List<DiskInfo> diskInfos = new();
 35 
 36         if (IsUnix())
 37         {
 38             try
 39             {
 40                 string output = ShellHelper.Bash("df -m / | awk '{print $2,$3,$4,$5,$6}'");
 41                 var arr = output.Split('\n', StringSplitOptions.RemoveEmptyEntries);
 42                 if (arr.Length == 0) return diskInfos;
 43 
 44                 var rootDisk = arr[1].Split(' ', (char)StringSplitOptions.RemoveEmptyEntries);
 45                 if (rootDisk == null || rootDisk.Length == 0)
 46                 {
 47                     return diskInfos;
 48                 }
 49                 DiskInfo diskInfo = new()
 50                 {
 51                     DiskName = "/",
 52                     TotalSize = long.Parse(rootDisk[0]) / 1024,
 53                     Used = long.Parse(rootDisk[1]) / 1024,
 54                     AvailableFreeSpace = long.Parse(rootDisk[2]) / 1024,
 55                     AvailablePercent = decimal.Parse(rootDisk[3].Replace("%", ""))
 56                 };
 57                 diskInfos.Add(diskInfo);
 58             }
 59             catch (Exception ex)
 60             {
 61                 Console.WriteLine("获取磁盘信息出错了" + ex.Message);
 62             }
 63         }
 64         else
 65         {
 66             var driv = DriveInfo.GetDrives();
 67             foreach (var item in driv)
 68             {
 69                 try
 70                 {
 71                     var obj = new DiskInfo()
 72                     {
 73                         DiskName = item.Name,
 74                         TypeName = item.DriveType.ToString(),
 75                         TotalSize = item.TotalSize / 1024 / 1024 / 1024,
 76                         AvailableFreeSpace = item.AvailableFreeSpace / 1024 / 1024 / 1024,
 77                     };
 78                     obj.Used = obj.TotalSize - obj.AvailableFreeSpace;
 79                     obj.AvailablePercent = decimal.Ceiling(obj.Used / (decimal)obj.TotalSize * 100);
 80                     diskInfos.Add(obj);
 81                 }
 82                 catch (Exception ex)
 83                 {
 84                     Console.WriteLine("获取磁盘信息出错了" + ex.Message);
 85                     continue;
 86                 }
 87             }
 88         }
 89 
 90         return diskInfos;
 91     }
 92 
 93     public static bool IsUnix()
 94     {
 95         var isUnix = RuntimeInformation.IsOSPlatform(OSPlatform.OSX) || RuntimeInformation.IsOSPlatform(OSPlatform.Linux);
 96         return isUnix;
 97     }
 98 
 99     public static string GetCPURate()
100     {
101         string cpuRate;
102         if (IsUnix())
103         {
104             string output = ShellHelper.Bash("top -b -n1 | grep \"Cpu(s)\" | awk '{print $2 + $4}'");
105             cpuRate = output.Trim();
106         }
107         else
108         {
109             string output = ShellHelper.Cmd("wmic", "cpu get LoadPercentage");
110             cpuRate = output.Replace("LoadPercentage", string.Empty).Trim();
111         }
112         return cpuRate;
113     }
114 
115     /// <summary>
116     /// 获取系统运行时间
117     /// </summary>
118     /// <returns></returns>
119     public static string GetRunTime()
120     {
121         string runTime = string.Empty;
122         try
123         {
124             if (IsUnix())
125             {
126                 string output = ShellHelper.Bash("uptime -s").Trim();
127                 runTime = DateTimeHelper.FormatTime((DateTime.Now - output.ParseToDateTime()).TotalMilliseconds.ToString().Split('.')[0].ParseToLong());
128             }
129             else
130             {
131                 string output = ShellHelper.Cmd("wmic", "OS get LastBootUpTime/Value");
132                 string[] outputArr = output.Split('=', (char)StringSplitOptions.RemoveEmptyEntries);
133                 if (outputArr.Length == 2)
134                 {
135                     runTime = DateTimeHelper.FormatTime((DateTime.Now - outputArr[1].Split('.')[0].ParseToDateTime()).TotalMilliseconds.ToString().Split('.')[0].ParseToLong());
136                 }
137             }
138         }
139         catch (Exception ex)
140         {
141             Console.WriteLine("获取runTime出错" + ex.Message);
142         }
143         return runTime;
144     }
145 }
146 
147 /// <summary>
148 /// 内存信息
149 /// </summary>
150 public class MemoryMetrics
151 {
152     [JsonIgnore]
153     public double Total { get; set; }
154     [JsonIgnore]
155     public double Used { get; set; }
156     [JsonIgnore]
157     public double Free { get; set; }
158 
159     public string UsedRam { get; set; }
160     /// <summary>
161     /// CPU使用率%
162     /// </summary>
163     public string CPURate { get; set; }
164     /// <summary>
165     /// 总内存 GB
166     /// </summary>
167     public string TotalRAM { get; set; }
168     /// <summary>
169     /// 内存使用率 %
170     /// </summary>
171     public string RAMRate { get; set; }
172     /// <summary>
173     /// 空闲内存
174     /// </summary>
175     public string FreeRam { get; set; }
176 }
177 
178 public class DiskInfo
179 {
180     /// <summary>
181     /// 磁盘名
182     /// </summary>
183     public string DiskName { get; set; }
184     public string TypeName { get; set; }
185     public long TotalFree { get; set; }
186     public long TotalSize { get; set; }
187     /// <summary>
188     /// 已使用
189     /// </summary>
190     public long Used { get; set; }
191     /// <summary>
192     /// 可使用
193     /// </summary>
194     public long AvailableFreeSpace { get; set; }
195     public decimal AvailablePercent { get; set; }
196 }
197 
198 public class MemoryMetricsClient
199 {
200     #region 获取内存信息
201 
202     /// <summary>
203     /// windows系统获取内存信息
204     /// </summary>
205     /// <returns></returns>
206     public MemoryMetrics GetWindowsMetrics()
207     {
208         string output = ShellHelper.Cmd("wmic", "OS get FreePhysicalMemory,TotalVisibleMemorySize /Value");
209         var metrics = new MemoryMetrics();
210         var lines = output.Trim().Split('\n', (char)StringSplitOptions.RemoveEmptyEntries);
211 
212         if (lines.Length <= 0) return metrics;
213 
214         var freeMemoryParts = lines[0].Split('=', (char)StringSplitOptions.RemoveEmptyEntries);
215         var totalMemoryParts = lines[1].Split('=', (char)StringSplitOptions.RemoveEmptyEntries);
216 
217         metrics.Total = Math.Round(double.Parse(totalMemoryParts[1]) / 1024, 0);
218         metrics.Free = Math.Round(double.Parse(freeMemoryParts[1]) / 1024, 0);//m
219         metrics.Used = metrics.Total - metrics.Free;
220 
221         return metrics;
222     }
223 
224     /// <summary>
225     /// Unix系统获取
226     /// </summary>
227     /// <returns></returns>
228     public MemoryMetrics GetUnixMetrics()
229     {
230         string output = ShellHelper.Bash("free -m | awk '{print $2,$3,$4,$5,$6}'");
231         var metrics = new MemoryMetrics();
232         var lines = output.Split('\n', (char)StringSplitOptions.RemoveEmptyEntries);
233 
234         if (lines.Length <= 0) return metrics;
235 
236         if (lines != null && lines.Length > 0)
237         {
238             var memory = lines[1].Split(' ', (char)StringSplitOptions.RemoveEmptyEntries);
239             if (memory.Length >= 3)
240             {
241                 metrics.Total = double.Parse(memory[0]);
242                 metrics.Used = double.Parse(memory[1]);
243                 metrics.Free = double.Parse(memory[2]);//m
244             }
245         }
246         return metrics;
247     }
248     #endregion
249 }
 1 public class ShellHelper
 2 {
 3     /// <summary>
 4     /// linux 系统命令
 5     /// </summary>
 6     /// <param name="command"></param>
 7     /// <returns></returns>
 8     public static string Bash(string command)
 9     {
10         var escapedArgs = command.Replace("\"", "\\\"");
11         var process = new Process()
12         {
13             StartInfo = new ProcessStartInfo
14             {
15                 FileName = "/bin/bash",
16                 Arguments = $"-c \"{escapedArgs}\"",
17                 RedirectStandardOutput = true,
18                 UseShellExecute = false,
19                 CreateNoWindow = true,
20             }
21         };
22         process.Start();
23         string result = process.StandardOutput.ReadToEnd();
24         process.WaitForExit();
25         process.Dispose();
26         return result;
27     }
28 
29     /// <summary>
30     /// windows系统命令
31     /// </summary>
32     /// <param name="fileName"></param>
33     /// <param name="args"></param>
34     /// <returns></returns>
35     public static string Cmd(string fileName, string args)
36     {
37         string output = string.Empty;
38 
39         var info = new ProcessStartInfo();
40         info.FileName = fileName;
41         info.Arguments = args;
42         info.RedirectStandardOutput = true;
43 
44         using (var process = Process.Start(info))
45         {
46             output = process.StandardOutput.ReadToEnd();
47         }
48         return output;
49     }
50 }

 

posted @ 2024-06-24 15:17  乐 乐——1128  阅读(3)  评论(0编辑  收藏  举报