WMI连接到ManagementScope

时间:2016-04-21 06:21:16

标签: c# wmi

我用C#和WMI做了一些测试

我想知道连接到ManagementScope的目的是什么? 在我的测试中,无论我是否使用“scope.Connect()”,结果都是一样的。

ManagementScope scope = new ManagementScope("\\\\" + sServer +"\\root\\CIMV2", oConn);


//  scope.Connect() ;                   When should I use this? Code works without it....
//  if (scope.IsConnected)
//      Console.WriteLine("Scope connected");

ObjectQuery query = new ObjectQuery("SELECT FreeSpace FROM Win32_LogicalDisk where DeviceID = 'C:'");

ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);

ManagementObjectCollection queryCollection = searcher.Get();

foreach (ManagementObject m in queryCollection)
    {
    freeSpace = (ulong)m.GetPropertyValue("FreeSpace");

     Console.WriteLine (freeSpace)
     }

1 个答案:

答案 0 :(得分:0)

来自.Net源代码:

ManagementObjectSearcher.Get()方法调用Initialize方法:

public void Get(ManagementOperationObserver watcher)
{
    if (null == watcher)
        throw new ArgumentNullException ("watcher");

    Initialize ();
    // ... more code
}

并且Initialize()方法实际确认范围是否已正确初始化并连接到范围(如果没有):

private void Initialize()
{
    //If the query is not set yet we can't do it
    if (null == query)
        throw new InvalidOperationException();
       //If we're not connected yet, this is the time to do it...
     lock (this)
    {
        if (null == scope)
            scope = ManagementScope._Clone(null);
    }
      lock (scope)
    {
        if (!scope.IsConnected)
            scope.Initialize();
    }
}

因此,如果您使用Connect(),则无需亲自调用ManagementSearcherObject方法。但是,您仍然可以从另一个对象访问搜索者,然后您需要验证自己是否已连接到管理范围。

Connect()类的ManagementScope方法除了调用相同的Initialize()方法之外什么都不做:

    public void Connect ()
    {
        Initialize ();
    }

您可以看到它herehere