Get a disk volume serial number in C#

[serial number]

This example uses the GetVolumeInformation API function so get a disk volume’s serial number. It starts by using 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 volume’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,
        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, then its parameters return the disk’s:

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

Download Example   Follow me on Twitter   RSS feed   Donate

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

2 Responses to Get a disk volume serial number in C#

  1. Pingback: Get a hard drive serial number in C# - C# HelperC# Helper

Comments are closed.