Get a disk drive’s serial number in C#

This example uses the GetVolumeInformation API function. It starts by importing the System.Rumtime.InteropServices namespace and by declaring the API function.

using System.Runtime.InteropServices;
private static extern long GetVolumeInformation(
    string PathName, 
    StringBuilder VolumeNameBuffer, 
    UInt32 VolumeNameSize, 
    ref UInt32 VolumeSerialNumber, 
    ref UInt32 MaximumComponentLength, 
    ref UInt32 FileSystemFlags, 
    StringBuilder FileSystemNameBuffer, 
    UInt32 FileSystemNameSize);

When you enter a disk’s name (as in “C:\”) and click the program’s Get Information button, the following code executes.

private void btnGetInformation_Click(object sender, EventArgs e)
    string drive_letter = txtDisk.Text;
    drive_letter = drive_letter.Substring(0, 1) + ":\\";

    uint serial_number = 0;
    uint max_component_length = 0;
    StringBuilder sb_volume_name = new StringBuilder(256);
    UInt32 file_system_flags = new UInt32();
    StringBuilder sb_file_system_name = new StringBuilder(256);

    if (GetVolumeInformation(drive_letter, sb_volume_name, 
        (UInt32)sb_volume_name.Capacity, ref serial_number,
        ref max_component_length, ref file_system_flags,
        (UInt32)sb_file_system_name.Capacity) == 0)
            "Error getting volume information.", 
            "Error", MessageBoxButtons.OK, 
    } else {
        txtVolumeName.Text = sb_volume_name.ToString();
        txtSerialNumber.Text = serial_number.ToString();
        txtMaxComponentLength.Text = max_component_length.ToString();
        txtFileSystem.Text = sb_file_system_name.ToString();
        txtFlags.Text = "&&H" + file_system_flags.ToString("x");

The code initializes some variables and calls the GetVolumeInformation API function. If the function returns successfully, its parameters return the disk’s:

  • Volume name
  • Serial number
  • Maximum component length
  • File system type
  • Flags

The program simply displays the results in text boxes.

This entry was posted in system and tagged , , , , , , , , , , . Bookmark the permalink.

One Response to Get a disk drive’s serial number in C#

Leave a Reply

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