An introduction in retrieving WMI in C#

This is a short introduction into retrieving WMI information using hard drive serial and model numbers as an example.

An introduction in retrieving WMI in C#.

C#

Freeware

English

This is a short introduction into retrieving WMI information using hard drive serial and model numbers as an example.

Windows Management Instrumentation (WMI)

WMI is a very useful way of accessing a huge amount of data about your hardware and software on a windows PC. It has been included to varying degrees in every Microsoft OS since Windows 95.

In Microsoft’s own words:

Managing with WMI
Windows Management Instrumentation (WMI) is based on the Web-Based Enterprise Management (WBEM) initiative. Industry leaders formed the WBEM initiative to produce a framework for standardized, low-cost solutions to enterprise system management needs.
The purpose of WMI is to provide a standardized means for managing your computer system, be it a local computer or all the computers in an enterprise. In its simplest terms, management is little more than the collecting data about the state of a managed object on the computer system and altering the state of the managed object by changing the data stored about the object. A managed object can be a hardware entity, such as a memory array, port, or disk drive. It can also be a software entity, such as a service, user account, or page file.
WMI can manage the many components of a computer system. In managing a hard disk, you can use WMI to monitor the amount of free space remaining on the disk. You could also use WMI to remotely alter the state of the drive by deleting files, changing file security, or partitioning or formatting the drive. Using the WMI framework, you can create a management application that monitors an enterprise, provides event-based alerts, and allows a user to control different aspects of an enterprise.

The Code:

A great place to start with C# is always the using statements and any reference’s you need to make, so here they are:

You will need to add System.Managment as a reference (right click the references folder under your solution in VS and select System.Managment under the .NET tab).

using System;
using System.Collections;
using System.Management;

The collections will be used to gather information about multiple hard drives on a system and management will of course access the WMI 😉

Normally a struct would be used to contain the information about the hard drive but due to some issues I had that are beyond the scope of this article I have used a normal class to contain the information.

class HardDriveInfo
{
    private string modelNo = null;
    private string serialNo = null;
    private string type = null;

    public string ModelNo
    {
        get 
        {
            return modelNo;
        }
        set 
        {
            modelNo = value;
        }
    }
    public string SerialNo
    {
        get 
        {
            return serialNo;
        }
        set 
        {
            serialNo = value;
        }
    }
    public string Type
    {
        get 
        {
            return type;
        }
        set
        {
            type = value;
        }
    }
}

This class provides us with a convenient way to store and access all the information we have about a hard drive.

Now on to the main class:

class TestProgram
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        
        [STAThread]
        static void Main(string[] args)
        {

This is your usual boring entry point. For this example I’m just making a quick Console Application that will write the information to the console, it should be easy enough for you to port it over into a workable class.

            ArrayList AL_HardDrives = new ArrayList();

            ManagementObjectSearcher MOS_HDSearcher = new ManagementObjectSearcher("SELECT * FROM Win32_DiskDrive");

The AL_HardDrives is the array list that we will store the information about the hard drives in. The Management Object Searcher access the WMI information, it uses SQL query’s to obtain the appropriate information. As previously mentioned the WMI has a vast amount of information accessible from it, far too much to list here but at the end of this article I will provide some links to helpful resources.

	    foreach(ManagementObject MO_HD in MOS_HDSearcher.Get())
            {
                HardDriveInfo HDI = new HardDriveInfo();
                HDI.ModelNo    = MO_HD["Model"].ToString();
                HDI.Type        = MO_HD["InterfaceType"].ToString();

                AL_HardDrives.Add(HDI);
            }

The MOS_HDSearcher will return information about multiple hard drives if more than one is installed in a PC when the Get method is called. We need to retrieve each one of these separately so we get each Management Object separately and parse out the information in it to our hard drive class.

           MOS_HDSearcher = new ManagementObjectSearcher("SELECT * FROM Win32_PhysicalMedia");

            int i = 0;
            foreach(ManagementObject MO_HD in MOS_HDSearcher.Get())
            {
                HardDriveInfo HDI = (HardDriveInfo)AL_HardDrives[i];

                if (MO_HD["SerialNumber"] == null)
                    HDI.SerialNo = "None";
                else
                    HDI.SerialNo = MO_HD["SerialNumber"].ToString();
                ++i;
            }

“SELECT * FROM Win32_DiskDrive” only returns the model number and the interface type of the hard drive so we need to reprogram the MOS_HDSearcher with the “SELECT * FROM Win32_PhysicalMedia” query to retrieve the serial number and parse it into the appropriate hard drive information.

            foreach(HardDriveInfo hd in AL_HardDrives)
            {
                Console.WriteLine("Model\t\t: " + hd.ModelNo);
                Console.WriteLine("Type\t\t: " + hd.Type);
                Console.WriteLine("Serial No.\t: " + hd.SerialNo);
                Console.WriteLine();
            }

            Console.ReadLine();
        }
}

Finally we want to display the information about the hard drives and wait for the user to hit enter before closing. Don’t forget to put these two classes into a namespace as well.

So there you are, your very own little program to get hold of the information about a hard drive and the basis for getting any information from the WMI.

Practical Applications

The hard drive serial number is very useful for tying applications to a specific pc within licensing and activation code. The WMI has so much information in it that the uses for it are almost limitless from performance monitors to hardware detection and registry editors.

The major source for WMI information can be found at:

MSDN WMI

Nathan Pakovskie is an esteemed senior developer and educator in the tech community, best known for his contributions to Geekpedia.com. With a passion for coding and a knack for simplifying complex tech concepts, Nathan has authored several popular tutorials on C# programming, ranging from basic operations to advanced coding techniques. His articles, often characterized by clarity and precision, serve as invaluable resources for both novice and experienced programmers. Beyond his technical expertise, Nathan is an advocate for continuous learning and enjoys exploring emerging technologies in AI and software development. When he’s not coding or writing, Nathan engages in mentoring upcoming developers, emphasizing the importance of both technical skills and creative problem-solving in the ever-evolving world of technology. Specialties: C# Programming, Technical Writing, Software Development, AI Technologies, Educational Outreach

Leave a Reply

Your email address will not be published. Required fields are marked *

Back To Top