C#中使用ManagementClass获取本机信息
C#提供 ManagementClass来对机器的信息进行管理,可以通过设定不同的管理类来获得机器的基本信息。下面给出了一些基本的信息的获取方法,包括获取CPU数目,cpu频率,内存大小,硬盘大小。
private void GetLocalInfo()
{
string cpuCount;
string hdSize;
string memorysize;
//得到CPU信息
ManagementClass mcpu = new ManagementClass("Win32_Processor");
ManagementObjectCollection mncpu = mcpu.GetInstances();
cpuCount = mncpu.Count.ToString();
string[] cpuHz = new string[mncpu.Count];
int count = 0;
ManagementObjectSearcher MySearcher = new ManagementObjectSearcher("SELECT * FROM Win32_Processor");
foreach (ManagementObject MyObject in MySearcher.Get())
{
cpuHz[count] = MyObject.Properties["CurrentClockSpeed"].Value.ToString();
count++;
}
mncpu.Dispose();
mcpu.Dispose();
//得到硬盘信息
ManagementClass mcHD = new ManagementClass("Win32_DiskDrive");
ManagementObjectCollection moHD = mcHD.GetInstances();
foreach (ManagementObject tempob in moHD)
{
hdSize = tempob.Properties["Size"].Value.ToString();
}
moHD.Dispose();
mcHD.Dispose();
//得到内存信息
ManagementClass mcMemory = new ManagementClass("Win32_OperatingSystem");
ManagementObjectCollection 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();
}
ManagementClass 类
http://msdn.microsoft.com/zh-cn/library/system.management.managementclass(VS.80).aspx
转自:http://blog.sina.com.cn/s/blog_48a5b47d0100ajv7.html
请发表评论