WMI操作示例
利用WMI可以实现对本地及远程主机的信息获取及操作,本示例WMI的应用。
1 System.Management.ConnectionOptions options = new ConnectionOptions();
2 options.Username=@"lypower\Administrator";
3 options.Password=@"your password here ";
4 System.Management.ManagementScope ms = new ManagementScope(@"\\remoteIP\root\cimv2",options);
5
6 //Get Local PC - ProcessorId :
7 //Win32_Processor Win32_DiskDrive Win32_NetworkAdapterConfiguration Win32_OperatingSystem
8 ms = null;//if COMMENT this line(means you COMMENT all above), you get remote, else you get local information.
9 System.Management.ObjectQuery query= new ObjectQuery("select * from Win32_Processor");
10 System.Management.ManagementObjectSearcher mos = new ManagementObjectSearcher(ms,query);
11 System.Management.ManagementObjectCollection moc = mos.Get();
12 foreach(ManagementObject mo in moc)
13 {
14 Console.WriteLine(mo["ProcessorId"]);
15 }
删除ms=null及其上面的所有行,并将ManagementObjectSearcher的ms参数去掉,可以查Local的ProcessorID。
类似的,我们可以查询很多对象,如上面代码绿色注释部分等,查询语句类似SQL,这里叫WQL。
我们用ManagementClass类可以更方便的查询本地信息,如下面代码
/// <summary>
/// 获取本机的Mac地址
/// </summary>
private string GetLocalMacAddress()
{
//网卡的MAC地址
ManagementClass mcNetworkAdapterConfiguration = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection mocNetworkAdapterConfiguration = mcNetworkAdapterConfiguration.GetInstances();
string strReturn = "";
foreach (var mac in mocNetworkAdapterConfiguration)
{
if ((bool)mac["IPEnabled"])
{
strReturn = string.Format("{0}\r\n", mac["MacAddress"]);
}
}
return strReturn;
}
几个参考的链接
http://itgroup.blueshop.com.tw/HammerChou/PowerHammer?n=convew&i=2383
http://www.soaspx.com/dotnet/csharp/csharp_20100511_4285.html
http://www.csharphelp.com/2006/10/wmi-made-easy-for-c/
http://www.dotblogs.com.tw/jimmyyu/archive/2009/07/02/9074.aspx