Get a disk drive's serial number in C#

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

using System.Runtime.InteropServices;
...
[DllImport("kernel32.dll")]
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,
sb_file_system_name, (UInt32)sb_file_system_name.Capacity) == 0)
{
MessageBox.Show(
"Error getting volume information.",
"Error", MessageBoxButtons.OK,
MessageBoxIcon.Exclamation);
} else {
lblVolumeName.Text = sb_volume_name.ToString();
lblSerialNumber.Text = serial_number.ToString();
lblMaxComponentLength.Text = max_component_length.ToString();
lblFileSystem.Text = sb_file_system_name.ToString();
lblFlags.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

   

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments
  • No comments exist for this post.
Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.