日期:2009-07-06  浏览次数:20519 次

Windows Management Instrumentation (WMI) is a very powerful mechanism for getting information about your system. Not only the local system but also other systems on the network should you desire. To start using the WMI classes you will need to add a reference to System.Management and issue a using command for System.Management in your C# file.

using System.Management;


To get the information you require you create a SelectQuery object with your query string:

SelectQuery sq = new SelectQuery ("SELECT * FROM Win32_LogicalDisk");

There are many different namespaces and classes of information in WMI. This tutorial will only show the usage of a single class. That class is the Win32_LogicalDisk. In this query you can specify specific fields as well as add a where clause. Its very similar to the queries you would write against a database.

The rest of the code tells the WMI system to get the information and output the results in the console:

ManagementObjectSearcher mos = new ManagementObjectSearcher (sq);

ManagementObjectCollection myMOC = mos.Get();

foreach (ManagementObject myMO in myMOC)
{
    Console.WriteLine ("====================================================");
    Console.WriteLine ("DeviceID = " + myMO.Properties["DeviceID"].Value);
    Console.WriteLine ("====================================================");

    foreach (PropertyData propData in myMO.Properties)
    {
        foreach (QualifierData qualData in propData.Qualifiers)
        {
            if (qualData.Name == "key")
            {
                Console.Write ("** KEY ");
            }
        }

        Console.WriteLine (propData.Name + " = " + propData.Value);
    }
}


A couple of things of note. You can get the properties by name (as with DeviceID) or by enumerating through the entries in the collection. You also can look at the qualifiers to see which property is the key. In the Win32_LogicalDisk case the key is the DeviceID.

There will be more tutorials on WMI so check back often.

That's all there is to it.