C#提供ManagementClass来对机器的信息进行管理,可以通过设定不同的管理类来获得机器的基本信息。下面给出了一些基本的信息的获取方法,包括获取CPU数目,cpu频率,内存大小,硬盘大小。
private void GetLocalInfo()
{
string cpuCount;
string hdSize;
string memorysize;
//得到CPU信息
ManagementClass mcpu = newManagementClass("Win32_Processor");
ManagementObjectCollection mncpu = mcpu.GetInstances();
cpuCount = mncpu.Count.ToString();
string[] cpuHz = new string[mncpu.Count];
int count = 0;
ManagementObjectSearcher MySearcher = newManagementObjectSearcher("SELECT * FROM Win32_Processor");
foreach (ManagementObject MyObject in MySearcher.Get())
{
cpuHz[count] =MyObject.Properties["CurrentClockSpeed"].Value.ToString();
count++;
}
mncpu.Dispose();
mcpu.Dispose();
//得到硬盘信息
ManagementClass mcHD = newManagementClass("Win32_DiskDrive");
ManagementObjectCollection moHD = mcHD.GetInstances();
foreach (ManagementObject tempob in moHD)
{
hdSize = tempob.Properties["Size"].Value.ToString();
}
moHD.Dispose();
mcHD.Dispose();
//得到内存信息
ManagementClass mcMemory = newManagementClass("Win32_OperatingSystem");
ManagementOb jectCollection mocMemory = mcMemory.GetInstances();
double sizeall = 0;
foreach (ManagementObject mo in mocMemory)
{
if (mo.Properties["TotalVisibleMemorySize"].Value != null)
{
sizeall +=double.Parse(mo.Properties["TotalVisibleMemorySize"].Value.ToString());
}
}
memorysize = sizeall.ToString();
mocMemory.Dispose();
mcMemory.Dispose();
}