菜单

c#与WMI使用技能集

2019年5月3日 - 金沙编程资讯

     
 在.NET的等级次序中,有时候需求得到Computer的硬件的连带音信,在C#语言中必要利用ManagementClass那个类来开始展览有关操作。

ManagementClass类解析和C#什么样收获硬件的有关新闻,

     
 在.NET的类型中,有时候供给获得计算机的硬件的相干新闻,在C#语言中须要利用ManagementClass这么些类来拓展有关操作。

   现在先来介绍一下ManagementClass类,首先看一下类的再三再四结构:


 

    以后看一下MSDN对ManagementClass类的演讲,对代表三个通用消息模型
(CIM) 管理类。 管理类是
WMI 类,如 Win3二_LogicalDisk,
,该项目可代表三个磁盘驱动器,并 Win3二_Process, ,它代表的进度Notepad.exe 等。 此类的积极分子能够访问
WMI 数据,使用2个特定的 WMI 类路线。

 
1.
接下去大家来看一下ManagementClass类中部分比较常用的点子的源码:

 
壹.GetInstances():此情势存在七个重载

 上面提供一下GetInstances(EnumerationOptions
options)重载版本的代码:

 

public ManagementObjectCollection GetInstances(EnumerationOptions options) 
         { 
            if ((null == Path) || (null == Path.Path) || (0 == Path.Path.Length))
                 throw new InvalidOperationException(); 

            Initialize ( false );
            IEnumWbemClassObject enumWbem = null;

            EnumerationOptions o = (null == options) ? new EnumerationOptions() : (EnumerationOptions)options.Clone();
             o.EnsureLocatable = false; o.PrototypeOnly = false;

             SecurityHandler securityHandler    = null;
            int status                        = (int)ManagementStatus.NoError;

             try 
            {
                securityHandler = Scope.GetSecurityHandler(); 
                            status = scope.GetSecuredIWbemServicesHandler(Scope.GetIWbemServices() ).CreateInstanceEnum_(ClassName, 
                                                            o.Flags,
                                                             o.GetContext(), 
                                                            ref enumWbem
                                                              );
             }
            finally 
             {
                if (securityHandler != null) 
                    securityHandler.Reset(); 
            }

             if (status < 0)
            {
                 if ((status & 0xfffff000) == 0x80041000)
                     ManagementException.ThrowWithExtendedInfo((ManagementStatus)status); 
                else
                     Marshal.ThrowExceptionForHR(status); 
            } 

            return new ManagementObjectCollection(Scope, o, enumWbem); 
        }

  2.Get():

 

 下边提供一下Get()重载版本的代码:

 public ManagementObjectCollection Get() 
        {
            Initialize (); 
            IEnumWbemClassObject ew = null; 
            SecurityHandler securityHandler = scope.GetSecurityHandler();
            EnumerationOptions enumOptions = (EnumerationOptions)options.Clone(); 

            int status = (int)ManagementStatus.NoError;

            try 
            {
                if ((query.GetType() == typeof(SelectQuery)) && 
                    (((SelectQuery)query).Condition == null) &&
                    (((SelectQuery)query).SelectedProperties == null) &&
                    (options.EnumerateDeep == true))
                { 
                    enumOptions.EnsureLocatable = false; enumOptions.PrototypeOnly = false; 

                    if (((SelectQuery)query).IsSchemaQuery == false) 
                    {
                        status = scope.GetSecuredIWbemServicesHandler( scope.GetIWbemServices()  ).CreateInstanceEnum_(
                            ((SelectQuery)query).ClassName,
                            enumOptions.Flags, 
                            enumOptions.GetContext(),
                            ref ew); 
                    } 
                    else
                    { 
                        status = scope.GetSecuredIWbemServicesHandler(scope.GetIWbemServices() ).CreateClassEnum_(((SelectQuery)query).ClassName,
                            enumOptions.Flags,
                            enumOptions.GetContext(),
                            ref ew ); 
                    }
                } 
                else
                {
                    enumOptions.EnumerateDeep = true;
                    status = scope.GetSecuredIWbemServicesHandler(scope.GetIWbemServices() ).ExecQuery_(
                        query.QueryLanguage,
                        query.QueryString, 
                        enumOptions.Flags,
                        enumOptions.GetContext(), 
                        ref ew ); 
                }
            } 
            catch (COMException e)
            {
                //
                ManagementException.ThrowWithExtendedInfo(e); 
            }
            finally 
            { 
                securityHandler.Reset();
            } 

            if ((status & 0xfffff000) == 0x80041000)
            {
                ManagementException.ThrowWithExtendedInfo((ManagementStatus)status); 
            }
            else if ((status & 0x80000000) != 0) 
            { 
                Marshal.ThrowExceptionForHR(status);
            } 
            return new ManagementObjectCollection(scope, options, ew); 
        }

三.GetSubclasses():此方式存在多个重载版本

 上面提供一下GetSubclasses(EnumerationOptions options)重载版本的代码:

public ManagementObjectCollection GetSubclasses(EnumerationOptions options)
        { 
             if (null == Path) 
                throw new InvalidOperationException();

             Initialize ( false ) ;
             IEnumWbemClassObject enumWbem = null;
            EnumerationOptions o = (null == options) ? new EnumerationOptions() : (EnumerationOptions)options.Clone(); 
            o.EnsureLocatable = false; o.PrototypeOnly = false; 
            SecurityHandler securityHandler = null; 
             int status                        = (int)ManagementStatus.NoError;

            try
             { 
                 securityHandler = Scope.GetSecurityHandler();
                            status = scope.GetSecuredIWbemServicesHandler( Scope.GetIWbemServices() ).CreateClassEnum_(ClassName, 
                    o.Flags, 
                     o.GetContext(),
                    ref enumWbem); 
            }
            finally
             {
                if (securityHandler != null) 
                     securityHandler.Reset();
             } 

            if (status < 0)
             { 
                if ((status & 0xfffff000) == 0x80041000)
                    ManagementException.ThrowWithExtendedInfo((ManagementStatus)status);
                else
                     Marshal.ThrowExceptionForHR(status); 
            }

             return new ManagementObjectCollection(Scope, o, enumWbem); 
         }

 
以上是对ManagementClass类的一对什么人明,此类型的装有公共静态成员都是线程安全的。不保险具备实例成员都以线程安全的。

二.ManagementClass类的局地行使:

 1.获得CPU编号

        /// <summary>
        /// 获得CPU编号
        /// </summary>
        /// <returns></returns>
        public string GetCpuid()
        {
            var cpuid = string.Empty;
            var mc = new ManagementClass("Win32_Processor");
            var moc = mc.GetInstances();
            foreach (var o in moc)
            {
                var mo = (ManagementObject) o;
                cpuid = mo.Properties["ProcessorId"].Value.ToString();
            }
            return cpuid;
        }

二.收获硬盘类别号

        /// <summary>
        /// 获取硬盘序列号
        /// </summary>
        /// <returns></returns>
        public string GetDiskSerialNumber()
        {
            //这种模式在插入一个U盘后可能会有不同的结果,如插入我的手机时
            var hDid = string.Empty;
            var mc = new ManagementClass("Win32_DiskDrive");
            var moc = mc.GetInstances();
            foreach (var o in moc)
            {
                var mo = (ManagementObject) o;
                hDid = (string)mo.Properties["Model"].Value;
                //这名话解决有多个物理盘时产生的问题,只取第一个物理硬盘
                break;
            }
            return hDid;
        }

三.到手网卡硬件地址

        /// <summary>
        /// 获取网卡硬件地址
        /// </summary>
        /// <returns></returns> 
        public string GetMacAddress()
        {
            var mac = "";
            var mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
            var moc = mc.GetInstances();
            foreach (var o in moc)
            {
                var mo = (ManagementObject) o;
                if (!(bool) mo["IPEnabled"]) continue;
                mac = mo["MacAddress"].ToString();
                break;
            }
            return mac;
        }

4.获取IP地址

        /// <summary>
        /// 获取IP地址
        /// </summary>
        /// <returns></returns>
        public string GetIpAddress()
        {
            var st = string.Empty;
            var mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
            var moc = mc.GetInstances();
            foreach (var o in moc)
            {
                var mo = (ManagementObject) o;
                if (!(bool) mo["IPEnabled"]) continue;
                var ar = (Array)(mo.Properties["IpAddress"].Value);
                st = ar.GetValue(0).ToString();
                break;
            }
            return st;
        }

伍.操作系统的登入用户名

        /// <summary>
        /// 操作系统的登录用户名
        /// </summary>
        /// <returns></returns> 
        public string GetUserName()
        {
            return Environment.UserName;
        }

六.获得Computer名

        /// <summary>
        /// 获取计算机名
        /// </summary>
        /// <returns></returns>
        public string GetComputerName()
        {
            return Environment.MachineName;
        }

柒.操作系统类型

        /// <summary>
        /// 操作系统类型
        /// </summary>
        /// <returns></returns> 
        public string GetSystemType()
        {
            var st = string.Empty;
            var mc = new ManagementClass("Win32_ComputerSystem");
            var moc = mc.GetInstances();
            foreach (var o in moc)
            {
                var mo = (ManagementObject) o;
                st = mo["SystemType"].ToString();
            }
            return st;
        }

八.物理内存

       /// <summary>
        /// 物理内存
        /// </summary>
        /// <returns></returns>
        public string GetPhysicalMemory()
        {
            var st = string.Empty;
            var mc = new ManagementClass("Win32_ComputerSystem");
            var moc = mc.GetInstances();
            foreach (var o in moc)
            {
                var mo = (ManagementObject) o;
                st = mo["TotalPhysicalMemory"].ToString();
            }
            return st;
        }

9.显卡PNPDeviceID

       /// <summary>
        /// 显卡PNPDeviceID
        /// </summary>
        /// <returns></returns>
        public string GetVideoPnpid()
        {
            var st = "";
            var mos = new ManagementObjectSearcher("Select * from Win32_VideoController");
            foreach (var o in mos.Get())
            {
                var mo = (ManagementObject) o;
                st = mo["PNPDeviceID"].ToString();
            }
            return st;
        }

10.声卡PNPDeviceID

       /// <summary>
        /// 声卡PNPDeviceID
        /// </summary>
        /// <returns></returns>
        public string GetSoundPnpid()
        {
            var st = string.Empty;
            var mos = new ManagementObjectSearcher("Select * from Win32_SoundDevice");
            foreach (var o in mos.Get())
            {
                var mo = (ManagementObject) o;
                st = mo["PNPDeviceID"].ToString();
            }
            return st;
        }

1一.CPU版本新闻

        /// <summary>
        /// CPU版本信息
        /// </summary>
        /// <returns></returns>
        public string GetCpuVersion()
        {
            var st = string.Empty;
            var mos = new ManagementObjectSearcher("Select * from Win32_Processor");
            foreach (var o in mos.Get())
            {
                var mo = (ManagementObject) o;
                st = mo["Version"].ToString();
            }
            return st;
        }

1二.CPU名号消息

        /// <summary>
        /// CPU名称信息
        /// </summary>
        /// <returns></returns>
        public string GetCpuName()
        {
            var st = string.Empty;
            var driveId = new ManagementObjectSearcher("Select * from Win32_Processor");
            foreach (var o in driveId.Get())
            {
                var mo = (ManagementObject) o;
                st = mo["Name"].ToString();
            }
            return st;
        }

1三. CPU创造厂家

        /// <summary>
        /// CPU制造厂商
        /// </summary>
        /// <returns></returns>
        public string GetCpuManufacturer()
        {
            var st = string.Empty;
            var mos = new ManagementObjectSearcher("Select * from Win32_Processor");
            foreach (var o in mos.Get())
            {
                var mo = (ManagementObject) o;
                st = mo["Manufacturer"].ToString();
            }
            return st;
        }

1四.主板创设厂家

        /// <summary>
        /// 主板制造厂商
        /// </summary>
        /// <returns></returns>
        public string GetBoardManufacturer()
        {
            var query = new SelectQuery("Select * from Win32_BaseBoard");
            var mos = new ManagementObjectSearcher(query);
            var data = mos.Get().GetEnumerator();
            data.MoveNext();
            var board = data.Current;
            return board.GetPropertyValue("Manufacturer").ToString();
        }

15.主板编号

        /// <summary>
        /// 主板编号
        /// </summary>
        /// <returns></returns>
        public string GetBoardId()
        {
            var st = string.Empty;
            var mos = new ManagementObjectSearcher("Select * from Win32_BaseBoard");
            foreach (var o in mos.Get())
            {
                var mo = (ManagementObject) o;
                st = mo["SerialNumber"].ToString();
            }
            return st;
        }

16.主板型号

        /// <summary>
        /// 主板型号
        /// </summary>
        /// <returns></returns>
        public string GetBoardType()
        {
            var st = string.Empty;
            var mos = new ManagementObjectSearcher("Select * from Win32_BaseBoard");
            foreach (var o in mos.Get())
            {
                var mo = (ManagementObject) o;
                st = mo["Product"].ToString();
            }
            return st;
        }

 
 以上的得到硬件音信的主意能够一向封装在三个类中,能够在品种中一向引用,这样可以加速项目标花费速度。

在.NET的花色中,有时候需求得到Computer的硬件的有关新闻,在C#语言中要求选拔Managemen…

1、
什么是WMI 
WMI是英文Windows Management
Instrumentation的简写,它的效率主若是:访问本地主机的有些音信和劳务,能够处理远程Computer(当然你必要求享有丰硕的权柄),比方:重启,关机,关闭进程,创立进度等。 
二、 怎么着用WMI获得本地球磁性盘的音讯? 
先是要在VS.NET中创制3个门类,然后在抬高引用中引用四个.net的装配件:System.Management.dll,那样您的品类才干运用WMI。代码如下: 
using System; 
using System.Management; 

   今后先来介绍一下ManagementClass类,首先看一下类的接轨结构:

class Sample_ManagementObject 

public static int Main(string[] args) 

SelectQuery query=new SelectQuery(“Select * From
Win32_LogicalDisk”); 
ManagementObjectSearcher searcher=new
ManagementObjectSearcher(query); 
foreach(ManagementBaseObject disk in searcher.Get()) 

Console.WriteLine(“\r\n”+disk[“Name”] +” “+disk[“DriveType”] + ” “

**图片 1**

 

Console.ReadLine(); 
return 0; 


disk[“DriveType”] 的重返值意义如下: 
1 No type 
2 Floppy disk 
3 Hard disk 
4 Removable drive or network drive 
5 CD-ROM 
6 RAM disk 

    以后看一下MSDN对ManagementClass类的表达,对表示三个通用消息模型
(CIM) 管理类。 管理类是
WMI 类,如 Win32_LogicalDisk,
,该品种可代表2个磁盘驱动器,并 Win3二_Process, ,它表示的经过
Notepad.exe 等。 此类的成员能够访问
WMI 数据,使用贰个一定的 WMI 类路线。

叁、怎么着用WMI得到内定磁盘的体积? 
using System; 
using System.Management; 
// This example demonstrates reading a property of a
ManagementObject. 
class Sample_ManagementObject 

public static int Main(string[] args) 

ManagementObject disk = new ManagementObject( 
“win32_logicaldisk.deviceid=\”c:\””); 
disk.Get(); 
Console.WriteLine(“Logical Disk Size = ” + disk[“Size”] + ”
bytes”); 
Console.ReadLine(); 
return 0; 

 
一.
接下去我们来看一下ManagementClass类中部分相比较常用的主意的源码:

四、 怎么样列出机器中兼有的共享财富? 
using System; 
using System.Management; 
class TestApp { 
[STAThread] 
static void Main() 

ManagementObjectSearcher searcher = new ManagementObjectSearcher( 
“SELECT * FROM Win32_share”); 
foreach (ManagementObject share in searcher.Get()) 

Console.WriteLine(share.GetText(TextFormat.Mof)); 

 
一.GetInstances():此措施存在四个重载


别忘记在引用中把System.Management增多进来。 

图片 2 上边提供一下GetInstances(EnumerationOptions
options)重载版本的代码:

5、 怎样写程序调控制让系统中的某些文件夹共享或裁撤共享.? 
第三,那需求以有对应权限的用户登6种类才行。然后,试试上面包车型客车代码: 
using System; 
using System.Management; 
class CreateShare 

public static void Main(string[] args) 

ManagementClass _class = new ManagementClass(new
ManagementPath(“Win32_Share”)); 
object[] obj = {“C:\\Temp”,”笔者的共享”,0,十,”Dot Net
完结的共享”,””}; 
_class.InvokeMethod(“create”,obj); 


将 
object[] obj = {“C:\\Temp”,”我的共享”,0,10,”Dot Net
落成的共享”,””}; 
改为 
object[] obj = {“C:\\Temp”,”笔者的共享”,0,null,”Dot Net
达成的共享”,””}; 
就可以完成授权给最多用户了。 

 

6、 如何赢得系统服务的运作情形? 
private void getServices() 

ManagementObjectCollection queryCollection; 
string[] lvData = new string[4]; 
try 

queryCollection = getServiceCollection(“SELECT * FROM
Win32_Service”); 
foreach ( ManagementObject mo in queryCollection) 

//create child node for operating system 
lvData[0] = mo[“Name”].ToString(); 
lvData[1] = mo[“StartMode”].ToString(); 
if (mo[“Started”].Equals(true)) 
lvData[2] = “Started”; 
else 
lvData[2] = “Stop”; 
lvData[3] = mo[“StartName”].ToString(); 
//create list item 
ListViewItem lvItem = new ListViewItem(lvData,0); 
listViewServices.Items.Add(lvItem); 


catch (Exception e) 

MessageBox.Show(“Error: ” + e); 

public ManagementObjectCollection GetInstances(EnumerationOptions options) 
         { 
            if ((null == Path) || (null == Path.Path) || (0 == Path.Path.Length))
                 throw new InvalidOperationException(); 

            Initialize ( false );
            IEnumWbemClassObject enumWbem = null;

            EnumerationOptions o = (null == options) ? new EnumerationOptions() : (EnumerationOptions)options.Clone();
             o.EnsureLocatable = false; o.PrototypeOnly = false;

             SecurityHandler securityHandler    = null;
            int status                        = (int)ManagementStatus.NoError;

             try 
            {
                securityHandler = Scope.GetSecurityHandler(); 
                            status = scope.GetSecuredIWbemServicesHandler(Scope.GetIWbemServices() ).CreateInstanceEnum_(ClassName, 
                                                            o.Flags,
                                                             o.GetContext(), 
                                                            ref enumWbem
                                                              );
             }
            finally 
             {
                if (securityHandler != null) 
                    securityHandler.Reset(); 
            }

             if (status < 0)
            {
                 if ((status & 0xfffff000) == 0x80041000)
                     ManagementException.ThrowWithExtendedInfo((ManagementStatus)status); 
                else
                     Marshal.ThrowExceptionForHR(status); 
            } 

            return new ManagementObjectCollection(Scope, o, enumWbem); 
        }

柒、 通过WMI修改IP,而落实不用再行起动? 
using System; 
using System.Management; 
using System.Threading; 
namespace WmiIpChanger 

class IpChanger 

[MTAThread] 
static void Main(string[] args) 

ReportIP(); 
// SwitchToDHCP(); 
SwitchToStatic(); 
Thread.Sleep( 5000 ); 
ReportIP(); 
Console.WriteLine( “end.” ); 

static void SwitchToDHCP() 

ManagementBaseObject inPar = null; 
ManagementBaseObject outPar = null; 
ManagementClass mc = new
ManagementClass(“Win32_NetworkAdapterConfiguration”); 
ManagementObjectCollection moc = mc.GetInstances(); 
foreach( ManagementObject mo in moc ) 

if( ! (bool) mo[“IPEnabled”] ) 
continue; 
inPar = mo.GetMethodParameters(“EnableDHCP”); 
outPar = mo.InvokeMethod( “EnableDHCP”, inPar, null ); 
break; 


static void SwitchToStatic() 

ManagementBaseObject inPar = null; 
ManagementBaseObject outPar = null; 
ManagementClass mc = new
ManagementClass(“Win32_NetworkAdapterConfiguration”); 
ManagementObjectCollection moc = mc.GetInstances(); 
foreach( ManagementObject mo in moc ) 

if( ! (bool) mo[ “IPEnabled” ] ) 
continue; 
inPar = mo.GetMethodParameters( “EnableStatic” ); 
inPar[“IPAddress”] = new string[] { “192.168.1.1” }; 
inPar[“SubnetMask”] = new string[] { “255.255.255.0” }; 
outPar = mo.InvokeMethod( “EnableStatic”, inPar, null ); 
break; 


static void ReportIP() 

Console.WriteLine( “****** Current IP addresses:” ); 
ManagementClass mc = new
ManagementClass(“Win32_NetworkAdapterConfiguration”); 
ManagementObjectCollection moc = mc.GetInstances(); 
foreach( ManagementObject mo in moc ) 

if( ! (bool) mo[ “IPEnabled” ] ) 
continue; 
Console.WriteLine( “{0}\n SVC: ‘{1}’ MAC: [{2}]”, (string)
mo[“Caption”], 
(string) mo[“ServiceName”], (string) mo[“MACAddress”] ); 
string[] addresses = (string[]) mo[ “IPAddress” ]; 
string[] subnets = (string[]) mo[ “IPSubnet” ]; 
Console.WriteLine( ” Addresses :” ); 
foreach(string sad in addresses) 
Console.WriteLine( “\t'{0}'”, sad ); 
Console.WriteLine( ” Subnets :” ); 
foreach(string sub in subnets ) 
Console.WriteLine( “\t'{0}'”, sub ); 



  2.Get():

八、 怎样行使WMI远程重启远程计算机? 
using System; 
using System.Management; 
namespace WMI3 

/// <summary> 
/// Summary description for Class1. 
/// </summary> 
class Class1 

static void Main(string[] args) 

Console.WriteLine(“Computer details retrieved using Windows Management
Instrumentation (WMI)”); 
Console.WriteLine(“mailto:Written%2002/01/02%20By%20John%20O’Donnell%20-%20csharpconsulting@hotmail.com”); 
Console.WriteLine(“======================================== 
=================================”); 
//连接远程Computer 
ConnectionOptions co = new ConnectionOptions(); 
co.Username = “john”; 
co.Password = “john”; 
System.Management.ManagementScope ms = new
System.Management.ManagementScope(“\\\\192.168.1.2\\root\\cimv2”,
co); 
//查询远程计算机 
System.Management.ObjectQuery oq = new
System.Management.ObjectQuery(“SELECT * FROM
Win32_OperatingSystem”); 
ManagementObjectSearcher query1 = new
ManagementObjectSearcher(ms,oq); 
ManagementObjectCollection queryCollection1 = query1.Get(); 
foreach( ManagementObject mo in queryCollection1 ) 

string[] ss={“”}; 
mo.InvokeMethod(“Reboot”,ss); 
Console.WriteLine(mo.ToString()); 



 图片 3

玖、 利用WMI创制2个新的进度? 
using System; 
using System.Management; 
// This sample demonstrates invoking a WMI method using parameter
objects 
public class InvokeMethod 

public static void Main() 

//Get the object on which the method will be invoked 
ManagementClass processClass = new ManagementClass(“Win32_Process”); 
//Get an input parameters object for this method 
ManagementBaseObject inParams =
processClass.GetMethodParameters(“Create”); 
//Fill in input parameter values 
inParams[“CommandLine”] = “calc.exe”; 
//Execute the method 
ManagementBaseObject outParams = processClass.InvokeMethod (“Create”,
inParams, null); 
//Display results 
//Note: The return code of the method is provided in the “returnvalue”
property of the outParams object 
Console.WriteLine(“Creation of calculator process returned: ” +
outParams[“returnvalue”]); 
Console.WriteLine(“Process ID: ” + outParams[“processId”]); 

 上边提供一下Get()重载版本的代码:

拾、 怎样通过WMI终止一个进程? 
using System; 
using System.Management; 
// This example demonstrates how to stop a system service. 
class Sample_InvokeMethodOptions 

public static int Main(string[] args) { 
ManagementObject service = 
new ManagementObject(“win32_service=\”winmgmt\””); 
InvokeMethodOptions options = new InvokeMethodOptions(); 
options.Timeout = new TimeSpan(0,0,0,5); 
ManagementBaseObject outParams = service.InvokeMethod(“StopService”,
null, options); 
Console.WriteLine(“Return Status = ” + outParams[“Returnvalue”]); 
return 0; 

 public ManagementObjectCollection Get() 
        {
            Initialize (); 
            IEnumWbemClassObject ew = null; 
            SecurityHandler securityHandler = scope.GetSecurityHandler();
            EnumerationOptions enumOptions = (EnumerationOptions)options.Clone(); 

            int status = (int)ManagementStatus.NoError;

            try 
            {
                if ((query.GetType() == typeof(SelectQuery)) && 
                    (((SelectQuery)query).Condition == null) &&
                    (((SelectQuery)query).SelectedProperties == null) &&
                    (options.EnumerateDeep == true))
                { 
                    enumOptions.EnsureLocatable = false; enumOptions.PrototypeOnly = false; 

                    if (((SelectQuery)query).IsSchemaQuery == false) 
                    {
                        status = scope.GetSecuredIWbemServicesHandler( scope.GetIWbemServices()  ).CreateInstanceEnum_(
                            ((SelectQuery)query).ClassName,
                            enumOptions.Flags, 
                            enumOptions.GetContext(),
                            ref ew); 
                    } 
                    else
                    { 
                        status = scope.GetSecuredIWbemServicesHandler(scope.GetIWbemServices() ).CreateClassEnum_(((SelectQuery)query).ClassName,
                            enumOptions.Flags,
                            enumOptions.GetContext(),
                            ref ew ); 
                    }
                } 
                else
                {
                    enumOptions.EnumerateDeep = true;
                    status = scope.GetSecuredIWbemServicesHandler(scope.GetIWbemServices() ).ExecQuery_(
                        query.QueryLanguage,
                        query.QueryString, 
                        enumOptions.Flags,
                        enumOptions.GetContext(), 
                        ref ew ); 
                }
            } 
            catch (COMException e)
            {
                //
                ManagementException.ThrowWithExtendedInfo(e); 
            }
            finally 
            { 
                securityHandler.Reset();
            } 

            if ((status & 0xfffff000) == 0x80041000)
            {
                ManagementException.ThrowWithExtendedInfo((ManagementStatus)status); 
            }
            else if ((status & 0x80000000) != 0) 
            { 
                Marshal.ThrowExceptionForHR(status);
            } 
            return new ManagementObjectCollection(scope, options, ew); 
        }

11、 怎么着用WMI
来收获远程机器的目录以及文件.例如咋样列出一个目录下的有着文件,或然全体子目录;如何删除,舔加,改换文件? 
using System; 
using System.Management; 
// This example demonstrates reading a property of a
ManagementObject. 
class Sample_ManagementObject 

public static int Main(string[] args) { 
ManagementObject disk = new ManagementObject( 
“win32_logicaldisk.deviceid=\”c:\””); 
disk.Get(); 
Console.WriteLine(“Logical Disk Size = ” + disk[“Size”] + ”
bytes”); 
return 0; 


1三、 一些技能 
自家利用WMI能够抽出网卡的MAC地址,CPU的类别号,主板的种类号,个中主板的连串号已经济审查结过没错的,别的的有待验证,因为本人利用的是台式机,台式机背面有2个主板的体系号,所以能够肯定主板种类号没不常常 
网卡的MAC地址 
SELECT MACAddress FROM Win32_NetworkAdapter WHERE ((MACAddress Is Not
NULL) AND (Manufacturer <> ‘Microsoft’)) 
结果:08:00:46:63:FF:8C 

三.GetSubclasses():此方法存在多个重载版本

CPU的文山会海号 
Select ProcessorId From Win32_Processor 
结果:3FEBF9FF00000F24 

图片 4

主板的多种号 
Select SerialNumber From Win32_BIOS 
结果:28362630-3700521 
获得硬盘ID 
String HDid; 
ManagementClass cimobject = new ManagementClass(“Win32_DiskDrive”); 
ManagementObjectCollection moc = cimobject.GetInstances(); 
foreach(ManagementObject mo in moc) 

HDid = (string)mo.Properties[“Model”].value; 
MessageBox.Show(HDid ); 

 上边提供一下GetSubclasses(EnumerationOptions options)重载版本的代码:

14、 3个用到WMI后的不得了管理的主题素材 
下边是本身整理的1段代码. 
ManagementObjectCollection queryCollection1; 
ConnectionOptions co = new ConnectionOptions(); 
co.Username = “administrator”; 
co.Password = “111”; 
try 

System.Management.ManagementScope ms = new
System.Management.ManagementScope(@”\\csnt3\root\cimv2″, co); 
System.Management.ObjectQuery oq = new
System.Management.ObjectQuery(“SELECT * FROM
Win32_OperatingSystem”); 
ManagementObjectSearcher query1 = new
ManagementObjectSearcher(ms,oq); 
queryCollection1 = query1.Get(); 
foreach( ManagementObject mo in queryCollection1 ) 

string[] ss={“”}; 
mo.InvokeMethod(“Reboot”,ss); 
Console.WriteLine(mo.ToString()); 


catch(Exception ee) 

Console.WriteLine(“error”); 

public ManagementObjectCollection GetSubclasses(EnumerationOptions options)
        { 
             if (null == Path) 
                throw new InvalidOperationException();

             Initialize ( false ) ;
             IEnumWbemClassObject enumWbem = null;
            EnumerationOptions o = (null == options) ? new EnumerationOptions() : (EnumerationOptions)options.Clone(); 
            o.EnsureLocatable = false; o.PrototypeOnly = false; 
            SecurityHandler securityHandler = null; 
             int status                        = (int)ManagementStatus.NoError;

            try
             { 
                 securityHandler = Scope.GetSecurityHandler();
                            status = scope.GetSecuredIWbemServicesHandler( Scope.GetIWbemServices() ).CreateClassEnum_(ClassName, 
                    o.Flags, 
                     o.GetContext(),
                    ref enumWbem); 
            }
            finally
             {
                if (securityHandler != null) 
                     securityHandler.Reset();
             } 

            if (status < 0)
             { 
                if ((status & 0xfffff000) == 0x80041000)
                    ManagementException.ThrowWithExtendedInfo((ManagementStatus)status);
                else
                     Marshal.ThrowExceptionForHR(status); 
            }

             return new ManagementObjectCollection(Scope, o, enumWbem); 
         }

1伍、Windows 管理标准 (WMI)
是可伸缩的系统管理结构,它应用多个统一的、基于专门的学问的、可扩张的面向对象接口。WMI
为您提供与系统一管理理音讯和基本功 WMI API 交互的正统方法。WMI
首要由系统管理应用程序开垦职员和大班用来访问和操作系统管理音讯。 
WMI
可用于转移组织和管理类别音信的工具,使管理员或系统管理职员能够更周全地监视系统活动。比方,能够接纳WMI 开拓2个应用程序,用于在 Web 服务器崩溃时呼叫助理馆员。 
将 WMI 与 .NET 框架一同行使 
WMI 提供了多量的正规化以便为众多高级应用程序(举个例子,Microsoft
Exchange、Microsoft SQL Server 和 Microsoft Internet 音信服务
(IIS))落成差不多任何管理职分。管理员能够试行下列任务: 
? 监视应用程序的运转情形。 
? 检查评定瓶颈或故障。 
? 管理和布局应用程序。 
? 查询应用程序数据(使用对象关联的遍历和查询)。 
? 实施无缝的本土或远程处理操作。 
WMI 结构由以下三层组成: 
? 客户端 
使用 WMI
实行操作(举个例子,读取管理详细音信、配置类别和预订事件)的软件组件。 
? 对象管理器 
提供程序与客户端之间的中档装置,它提供一些首要服务,如正式事件发表和预约、事件筛选、查询引擎等。 
? 提供程序 
软件组件,它们捕获实时数据并将其归来到客户端应用程序,管理来自客户端的主意调用并将客户端链接到所管理的基本功结构。 
透过定义完善的架构向客户端和应用程序无缝地提供了数据和事件以及布置类别的力量。在
.NET 框架中,System.Management 命名空间提供了用来遍历 WMI
架构的公共类。 
除了 .NET 框架,还需求在Computer上设置 WMI
本领应用该命名空间中的管理成效。借使利用的是 Windows 米尔ennium
Edition、Windows 3000 或 Windows XP,那么早就设置了 WMI。不然,将要求从
MSDN 下载 WMI。 
用 System.Management 访问管理消息 
System.Management 命名空间是 .NET 框架中的 WMI
命名空间。此命名空间包涵下列辅助 WMI 操作的第一级类对象: 
? ManagementObject 或 ManagementClass:分别为单个管理对象或类。 
? ManagementObjectSearcher:用于根据内定的询问或枚举检索
ManagementObject 或 ManagementClass 对象的联谊。 
? Management伊夫nt沃特cher:用于预约来自 WMI 的事件通报。 
? ManagementQuery:用作全数查询类的功底。 
System.Management 类的应用编码轨范对 .NET 框架碰着很适合,并且 WMI
在其余方便的时候均选用标准基框架。比如,WMI 普及应用 .NET
会集类并运用推荐的编码格局,如 .NET 异步操作的“委托”方式。由此,使用
.NET
框架的开垦职员能够动用他们的脚下本事访问有关计算机或应用程序的保管音讯。 
请参见 
运用 WMI 管理应用程序 | 检索管理对象的集合 | 查询管理新闻 |
预约和行使处监护人件 | 施行处理对象的不二秘诀 | 远程管理和连接选项 |
使用强类型对象 获取CPU类别号代码 
string cpuInfo = “”;//cpu序列号 
ManagementClass cimobject = new ManagementClass(“Win32_Processor”); 
ManagementObjectCollection moc = cimobject.GetInstances(); 
foreach(ManagementObject mo in moc) 

cpuInfo = mo.Properties[“ProcessorId”].value.ToString(); 
Console.WriteLine(cpuInfo); 
Console.ReadLine(); 

获取网卡硬件地址 
using System.Management; 
… 
ManagementClass mc = new
ManagementClass(“Win32_NetworkAdapterConfiguration”); 
ManagementObjectCollection moc = mc.GetInstances(); 
foreach(ManagementObject mo in moc) 

if((bool)mo[“IPEnabled”] == true) 
Console.WriteLine(“MAC address\t{0}”,
mo[“MacAddress”].ToString()); 
mo.Dispose(); 


收获硬盘ID 
String HDid; 
ManagementClass cimobject = new ManagementClass(“Win32_DiskDrive”); 
ManagementObjectCollection moc = cimobject.GetInstances(); 
foreach(ManagementObject mo in moc) 

HDid = (string)mo.Properties[“Model”].value; 
MessageBox.Show(HDid ); 

相关文章

发表评论

电子邮件地址不会被公开。 必填项已用*标注

网站地图xml地图