Title: Get a disk volume serial number in C#
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;
...
[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 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,
sb_file_system_name,
(UInt32)sb_file_system_name.Capacity) == 0)
{
MessageBox.Show(
"Error getting volume information.",
"Error", MessageBoxButtons.OK,
MessageBoxIcon.Exclamation);
}
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, then its parameters return the disk's:
- Volume name
- Serial number
- Maximum component length
- File system type
- Flags
Download the example to experiment with it and to see additional details.
|