Disk Drive Dangers - SMART and WMI
Written by Mike James   
Monday, 01 July 2024
Article Index
Disk Drive Dangers - SMART and WMI
WMI Query Language
Get Smart
Decoding WMI data
Processing the data
Listing

Place a button on the form and enter all of the following code into its click event handler.

First we need a ManagementObjectSearcher object:

ManagementObjectSearcher WMISearch =
new ManagementObjectSearcher();

This will return a collection of WMI objects that match a search criterion specified as an ObjectQuery in its Query property. For example:

WMISearch.Query= new ObjectQuery(
"Select * from Win32_DiskDrive");

If you know any SQL you will see the similarity between WMI Query Language, for WSQ is indeed based on SQL.

The “*” is a “match all” condition and so all of the instances of the Win32_DiskDrive object are returned.

To actually retrieve the objects that match we use the Get method:

ManagementObjectCollection Drives =
WMISearch.Get();

The returned collection is always the same type irrespective of the actual type of the objects returned.

Now we can step through the drives collection and display whatever information interests us:

foreach ( ManagementObject Drive 
in Drives )
{
MessageBox.Show(
Drive.Properties["Name"].
Value.ToString());
}

Notice the way that we have to retrieve the properties of the Drive object using a lookup in an array. This is the only easy way to deal with the fact that each WMI object is different and has its own set of properties and methods.

In this case the name of each drive in the system is listed in a MessageBox:

 

drivelist

 

The full button click handler is:

private void button1_Click(object sender, EventArgs e)
        {
            ManagementObjectSearcher WMISearch =
new ManagementObjectSearcher();
            WMISearch.Query = new ObjectQuery(
"Select * from Win32_DiskDrive");
            ManagementObjectCollection Drives =
WMISearch.Get();
            foreach (ManagementObject Drive in Drives)
            {
                MessageBox.Show(
                      Drive.Properties["Name"].
Value.ToString());
            }
        }

So to summarize, using WMI from .NET is a matter of:

  1. Creating an instance of ManagementObjectSearcher
  2. Working out the appropriate query and using it
  3. Using properties and methods of the objects returned

This is fairly simple and in practice most of the difficulty in using WMI is finding out what the classes are, what properties and methods they support, and determining if they actually work as advertised.

It is also worth knowing that you can make a WQL query in one step using an alternative ManagementObjectSearcher constructor:

ManagementObjectSearcher WMISearch =
new ManagementObjectSearcher(
"Select * from Win32_DiskDrive");


<ASIN:0201616130>

<ASIN:1578702607>



Last Updated ( Monday, 01 July 2024 )