using System;
using System.Diagnostics;
class Program
{
static void Main(string[] args)
{
// 获取系统CPU利用率
PerformanceCounter cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total");
float cpuUsage = cpuCounter.NextValue();
System.Threading.Thread.Sleep(1000);
cpuUsage = cpuCounter.NextValue();
Console.WriteLine("CPU 使用率: {0}%", cpuUsage);
// 获取系统内存使用情况
PerformanceCounter ramCounter = new PerformanceCounter("Memory", "Available MBytes");
float availableMB = ramCounter.NextValue();
Console.WriteLine("系统可用内存:{0} MB", availableMB);
// 获取硬盘使用情况
foreach (DriveInfo drive in DriveInfo.GetDrives())
{
if (drive.IsReady)
{
Console.WriteLine("{0} 硬盘使用情况:", drive.Name);
Console.WriteLine("总容量:{0} GB", drive.TotalSize / 1024 / 1024 / 1024);
Console.WriteLine("已使用容量:{0} GB", (drive.TotalSize - drive.AvailableFreeSpace) / 1024 / 1024 / 1024);
Console.WriteLine("可用容量:{0} GB", drive.AvailableFreeSpace / 1024 / 1024 / 1024);
}
}
Console.ReadLine();
}
}
该代码首先使用 PerformanceCounter 类获取系统 CPU 利用率和内存可用容量,然后通过 DriveInfo 类获取硬盘使用情况。其中,CPU 利用率是通过“Processor”类的“% Processor Time”计数器获取的;内存可用容量是通过“Memory”类的“Available MBytes”计数器获取的。
需要注意的是,这里只对硬盘进行了简单的容量统计,并没有考虑磁盘分区、文件系统等因素。实际上,如果需要更加详细和准确的硬盘信息,可以使用 WMI(Windows Management Instrumentation)来获取。