Get Volume Label From Drive Number (Not Drive Letter)
See the question and my original answer on StackOverflowWhat you call a "drive number" is named "Disk Index" in WMI parlance. You shouldn't have to parse anything to establish relations between WMI classes.
You can only get a volume label from a Win32_LogicalDisk's VolumeName
property. It should work for mounted VHD(X) as well. The following code browses all partitions (note a disk can have multiple partitions) and dumps the associated logical disks (note a partition can have multiple logical disks) volume names, if any:
foreach (var partition in new ManagementObjectSearcher("SELECT * FROM Win32_DiskPartition").Get())
{
Console.WriteLine("Caption : " + partition["Caption"]);
Console.WriteLine("Disk Index : " + partition["DiskIndex"]);
// associate the partition with logical disk(s)
foreach (var logicalDisk in new ManagementObjectSearcher(
"ASSOCIATORS OF {Win32_DiskPartition.DeviceID='" +
partition["DeviceID"] +
"'} WHERE AssocClass=Win32_LogicalDiskToPartition").Get())
{
Console.WriteLine(" " + logicalDisk["VolumeName"]);
}
}
If you want partitions and volume names for a given disk, just restrict the initial query, like this: SELECT * FROM Win32_DiskPartition WHERE DiskIndex=1
for example.