|
@@ -0,0 +1,99 @@
|
|
|
+namespace CommonLibrary
|
|
|
+{
|
|
|
+ using System;
|
|
|
+ using System.Collections.Generic;
|
|
|
+ using System.Diagnostics;
|
|
|
+ using System.IO;
|
|
|
+ using Microsoft.VisualBasic.Devices;
|
|
|
+
|
|
|
+ public class ComputerUtil : IDisposable
|
|
|
+ {
|
|
|
+ private readonly PerformanceCounter cpu;
|
|
|
+
|
|
|
+ private readonly ComputerInfo cinf;
|
|
|
+
|
|
|
+ public ComputerUtil()
|
|
|
+ {
|
|
|
+ this.cpu = new PerformanceCounter("Processor", "% Processor Time", "_Total");
|
|
|
+ this.cinf = new ComputerInfo();
|
|
|
+ }
|
|
|
+
|
|
|
+ /// <summary>
|
|
|
+ /// cpu 使用情况
|
|
|
+ /// </summary>
|
|
|
+ /// <returns>cpu利用率</returns>
|
|
|
+ public double GetCpuPercent()
|
|
|
+ {
|
|
|
+ var percentage = this.cpu.NextValue();
|
|
|
+ return Math.Round(percentage, 2, MidpointRounding.AwayFromZero);
|
|
|
+ }
|
|
|
+
|
|
|
+ /// <summary>
|
|
|
+ /// 内存使用情况
|
|
|
+ /// </summary>
|
|
|
+ /// <returns>内存使用率</returns>
|
|
|
+ public double GetMemoryPercent()
|
|
|
+ {
|
|
|
+ var usedMem = this.cinf.TotalPhysicalMemory - this.cinf.AvailablePhysicalMemory; // 总内存减去可用内存
|
|
|
+ return Math.Round(
|
|
|
+ (double)(usedMem / Convert.ToDecimal(this.cinf.TotalPhysicalMemory) * 100),
|
|
|
+ 2,
|
|
|
+ MidpointRounding.AwayFromZero);
|
|
|
+ }
|
|
|
+
|
|
|
+ public HardDiskInfo GetHardDiskInfoByName(string diskName)
|
|
|
+ {
|
|
|
+ DriveInfo drive = new DriveInfo(diskName);
|
|
|
+ return new HardDiskInfo { FreeSpace = this.GetDriveData(drive.AvailableFreeSpace), TotalSpace = this.GetDriveData(drive.TotalSize), Name = drive.Name };
|
|
|
+ }
|
|
|
+
|
|
|
+ public string FreeSpaceHardDisk()
|
|
|
+ {
|
|
|
+ long userDisk = 0;
|
|
|
+ foreach (var d in DriveInfo.GetDrives())
|
|
|
+ {
|
|
|
+ if (d.IsReady)
|
|
|
+ {
|
|
|
+ userDisk = userDisk + d.AvailableFreeSpace;
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ return this.GetDriveData(userDisk);
|
|
|
+ }
|
|
|
+
|
|
|
+ /// <summary>
|
|
|
+ /// 硬盘信息使用情况
|
|
|
+ /// </summary>
|
|
|
+ /// <returns>所有硬盘信息</returns>
|
|
|
+ public IEnumerable<HardDiskInfo> GetAllHardDiskInfo()
|
|
|
+ {
|
|
|
+ List<HardDiskInfo> infos = new List<HardDiskInfo>();
|
|
|
+ foreach (var d in DriveInfo.GetDrives())
|
|
|
+ {
|
|
|
+ if (d.IsReady)
|
|
|
+ {
|
|
|
+ HardDiskInfo h = new HardDiskInfo
|
|
|
+ {
|
|
|
+ Name = d.Name,
|
|
|
+ FreeSpace = this.GetDriveData(d.AvailableFreeSpace),
|
|
|
+ TotalSpace = this.GetDriveData(d.TotalSize)
|
|
|
+ };
|
|
|
+
|
|
|
+ infos.Add(h);
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ return infos;
|
|
|
+ }
|
|
|
+
|
|
|
+ public void Dispose()
|
|
|
+ {
|
|
|
+ this.cpu.Dispose();
|
|
|
+ }
|
|
|
+
|
|
|
+ private string GetDriveData(long data)
|
|
|
+ {
|
|
|
+ return (data / Convert.ToDouble(1024) / Convert.ToDouble(1024) / Convert.ToDouble(1024)).ToString("0.00");
|
|
|
+ }
|
|
|
+ }
|
|
|
+}
|