前言:
我们在很多情况下想要获得计算机的硬件或操作系统的信息,比如获得CPU序列号给自己的软件添加机器码锁绑定指定电脑。又或者想要获得硬盘分区,声卡显卡等信息。
开篇:
我们用到的主要类是ManagementObjectSearcher
,该类在System.Management
命名空间下。
有时候我们可以通过Environment
获得一些简单的系统信息。
如:Environment.MachineName;
获得计算机名。
Environment.UserName;
获得操作系统登录用户名。
不过在这篇文章中主要讨论ManagementObjectSearcher
获取计算机硬件及操作系统的信息。
用法步骤:
- 添加引用:
System.Management
- 引入命名空间:
using System.Management;
- 创建
ManagementObjectSearcher
对象
anagementObjectSearcher searcher = new ManagementObjectSearcher("select * from " + Key);
其中的key见下面key列表: - 通过
searcher.Get()
获得ManagementObjectCollection
集合 - 遍历
ManagementObjectCollection
集合获得ManagementObject
- 通过
managementObject[name]
或ManagementObject.GetPropertyValue(name)
获得想要的属性
若不知道这里的name
该写什么可以遍历打印一下:
foreach (var property in managementObject.Properties)
{
Console.WriteLine(property.Name+":"+property.Value);
}
- OK.
示例:
//获取CPU序列号
public string GetCPUSerialNumber()
{
try
{
ManagementObjectSearcher searcher = new ManagementObjectSearcher("Select * From Win32_Processor");
string sCPUSerialNumber = "";
foreach (ManagementObject mo in searcher.Get())
{
sCPUSerialNumber = mo["ProcessorId"].ToString().Trim();
break;
}
return sCPUSerialNumber;
}
catch
{
return "";
}
}
/获取主板序列号
public string GetBIOSSerialNumber()
{
try
{
ManagementObjectSearcher searcher = new ManagementObjectSearcher("Select * From Win32_BIOS");
string sBIOSSerialNumber = "";
foreach (ManagementObject mo in searcher.Get())
{
sBIOSSerialNumber = mo.GetPropertyValue("SerialNumber").ToString().Trim();
break;
}
return sBIOSSerialNumber;
}
catch
{
return "";
}
}
//获取硬盘序列号
public string GetHardDiskSerialNumber()
{
try
{
ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_PhysicalMedia");
string sHardDiskSerialNumber = "";
foreach (ManagementObject mo in searcher.Get())
{
sHardDiskSerialNumber = mo["SerialNumber"].ToString().Trim();
break;
}
return sHardDiskSerialNumber;
}
catch
{
return "";
}
}
//获取网卡地址
public string GetNetCardMACAddress()
{
try
{
ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_NetworkAdapter WHERE ((MACAddress Is Not NULL) AND (Manufacturer <> 'Microsoft'))");
string NetCardMACAddress = "";
foreach (ManagementObject mo in searcher.Get())
{
NetCardMACAddress = mo["MACAddress"].ToString().Trim();
break;
}
return NetCardMACAddress;
}
catch
{