public class DeviceMonitor { static readonly PerformanceCounter cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total"); static readonly PerformanceCounter ramCounter = new PerformanceCounter("Memory", "Available MBytes"); static readonly PerformanceCounter uptime = new PerformanceCounter("System", "System Up Time"); public static bool GetInternetAvilable() { bool networkUp = System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable(); return networkUp; } public static TimeSpan GetSystemUpTime() { uptime.NextValue(); TimeSpan ts = TimeSpan.FromSeconds(uptime.NextValue()); return ts; } public static string GetPhysicalMemory() { string str = null; ManagementObjectSearcher objCS = new ManagementObjectSearcher("SELECT * FROM Win32_ComputerSystem"); foreach (ManagementObject objMgmt in objCS.Get()) { str = objMgmt["totalphysicalmemory"].ToString(); } return str; } public static string getCurrentCpuUsage() { return cpuCounter.NextValue() + "%"; } public static string getAvailableRAM() { return ramCounter.NextValue() + "MB"; } }
显示:
Console.WriteLine("网络是否可用:" + DeviceMonitor.GetInternetAvilable()); Console.WriteLine("系统已运行时间:" + DeviceMonitor.GetSystemUpTime()); Console.WriteLine("物理总内存:" + (double.Parse(DeviceMonitor.GetPhysicalMemory())/(1024*1024*1024)).ToString("F2")+"GB" ); Console.WriteLine("当前CPU值:" + DeviceMonitor.getCurrentCpuUsage()); Console.WriteLine("当前可用内存:" + DeviceMonitor.getAvailableRAM());
效果:
源码地址:https://files.cnblogs.com/files/lizhijian/2021-01-05-%E8%8E%B7%E5%8F%96%E7%94%B5%E8%84%91%E7%8A%B6%E6%80%81.rar