Search code examples
c#wmi

WMI connect to ManagementScope


I do some tests with C# and WMI

I wonder what is the purpose of connecting to a ManagementScope ? In my tests there is no difference whether or not I use "scope.Connect()" , the result is the same.

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)
     }

Solution

  • From the .Net source code:

    The ManagementObjectSearcher.Get() method calls the Initialize method:

    public void Get(ManagementOperationObserver watcher)
    {
        if (null == watcher)
            throw new ArgumentNullException ("watcher");
    
        Initialize ();
        // ... more code
    }
    

    and the Initialize() method actually confirms if the scope has been initialized correctly and connects to the scope if it hasn't:

    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();
        }
    }
    

    So you do not have to call the Connect() method yourself if you use a ManagementSearcherObject. However you can still access the searcher from another object and then you need to verify yourself that you connected to your management scope.

    The Connect() method of the ManagementScope class however does nothing else but call the very same Initialize() method:

        public void Connect ()
        {
            Initialize ();
        }
    

    You can see it here and here