[C# Helper]
Index Books FAQ Contact About Rod
[Beginning Database Design Solutions, Second Edition]

[Beginning Software Engineering, Second Edition]

[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

Title: Get a hard drive serial number in C#

[Get a hard drive serial number in C#]

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()); } trvInfo.ExpandAll(); }

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 the example to experiment with it and to see additional details.

© 2009-2023 Rocky Mountain Computer Consulting, Inc. All rights reserved.