Monday, November 29, 2004 - Posts

Using WMI in .NET

I recently needed to write some code to determine the percentage of free disk space on a drive.  I was a bit surprised when I found that this information wasn't immediately available in some .NET class.  However, I did stumble upon the System.Management namespace.  This namespace contains classes that allow a .NET programmer to query any of the vast array of Windows Management Instrumentation (WMI) classes.  These classes allow a program to obtain all kinds of data about a system, including free and total disk space.

Here is some code that uses the ManagementObject class:

// get parms from the command line
DiskDrive = args[4].Replace(":","").ToUpper();

// run the query
mo = new ManagementObject(string.Format("Win32_LogicalDisk.DeviceID=\"{0}:\"", DiskDrive));

// store results
FreeSpace = double.Parse(mo["FreeSpace"].ToString());
TotalSpace = double.Parse(mo["Size"].ToString());

CurrentValue = (int)Math.Round((FreeSpace / TotalSpace) * 100, 0);

 

Now, the example above does a direct query against a single instance of a WMI class.  Sometimes this isn't possible.  Some WMI classes return multiple instances, which need to be iterated.  Here is an example that returns the status of a Windows Service:

// get parms from the command line
Service = args[2].ToString().ToUpper();

// run the query
Query = string.Format("select State,Name from Win32_BaseService where Name=\"{0}\"", Service);

mos = new ManagementObjectSearcher(Query);

// find the WMI instance for the indicated service
foreach (ManagementObject mo in mos.Get())
{
     Name = mo["Name"].ToString().ToUpper();

          if (Name == Service)
          {
               State = mo["State"].ToString();
          }
}

See here and here for two of the MSDN pages that I used most.