Get a hard drive serial number in C#

[serial number]

The example Get a disk volume serial number in C# shows how you can find the serial number for a disk volume such as C:\. If you reformat or repartition the drive, however, the volume serial number may change.

This example gets the hardware manufacturer’s serial number for the hard drive itself. That won’t change if you reformat the drive.

To build the example, I added a reference to System.Management. The code starts with a using System.Management directive.

When the program starts, the following code executes to display information about the system’s disk drives.

private void Form1_Load(object sender, EventArgs e)
    ManagementObjectSearcher searcher =
        new ManagementObjectSearcher("SELECT * FROM Win32_DiskDrive");

    foreach (ManagementObject info in searcher.Get())
        TreeNode node = trvInfo.Nodes.Add(info["DeviceID"].ToString());
        node.Nodes.Add("Model: " + info["Model"].ToString());
        node.Nodes.Add("Interface: " + info["InterfaceType"].ToString());
        node.Nodes.Add("Serial#: " + info["SerialNumber"].ToString());

This code creates a ManagementObjectSearcher to execute the query SELECT * FROM Win32_DiskDrive. It loops through the results and adds the results’ device ID, model, interface, and serial number to the program’s TreeView control.

Of course, if you’re only interested in the serial number, you can modify the program to display only that. To learn about other fields that you could display, see Microsoft’s page on the Win32_DiskDrive class.

Download Example   Follow me on Twitter   RSS feed   Donate

About RodStephens

Rod Stephens is a software consultant and author who has written more than 30 books and 250 magazine articles covering C#, Visual Basic, Visual Basic for Applications, Delphi, and Java.
This entry was posted in system and tagged , , , , , , , , , , , . Bookmark the permalink.

5 Responses to Get a hard drive serial number in C#

  1. passanger says:

    trvInfo ??
    it’s a String or ??

    • RodStephens says:

      “trv” is a prefix that means TreeView, so this is a TreeView control.

      Note that you can also download the example to see all of the details. (Although this is a relatively simple example so you may not need to download it, once you know what “trvInfo” means 😉 .)

  2. Asim says:

    great work ! thank you

  3. raviteja says:

    it will work when we publish the application to the server

Comments are closed.