Search code examples
c#.netfile-iosystem.managementdriveinfo

Map a DiskIndex to a Volume Label


Current I am able to get all the Drives and their labels in c# by using the DriveInfo.GetDrives(). Then I am able to get the Disk Index / Index of the Partition by this methodology.

var searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_DiskPartition");

foreach (var queryObj in searcher.Get())
{
    Console.WriteLine("-----------------------------------");
    Console.WriteLine("Win32_DiskPartition instance");
    Console.WriteLine("Name:{0}", (string)queryObj["Name"]);
    Console.WriteLine("Index:{0}", (uint)queryObj["Index"]);
    Console.WriteLine("DiskIndex:{0}", (uint)queryObj["DiskIndex"]);
    Console.WriteLine("BootPartition:{0}", (bool)queryObj["BootPartition"]);
}

The problem with this is that the DiskIndex, Name, and Index are basically just numbers and not the Volume Label i.e. C:\, D:\, etc...

So bottom line how can I make the Volume Label which is the Name Proprty on the DriveInfo to the DiskIndex? Either using this methodology or a better way will work.

(This is a follow to: Tell if a Drive is a partition or a separate HDD)

EDIT: I did find for the Management Query of the Win32_LogicalDisk and then the Win32_LogicalDiskToPartition. the LogicalDisk has the volume and the LogicalDisktoParition provides the mapping. However, I cannot seem to figure out how to get the map. I tried looking for a JOIN and selecting the values but couldn't find anything on how do this join without extensive looping in the c# code.


Solution

  • You need to use the Win32_LogicalDisk class.

    Edit: You are correct Win32_LogicalDiskToPartition. Is the link between Win32_LogicalDisk and Win32_DiskPartition. On Win32_LogicalDiskToPartition class, these two properties show the links,

    PS> Get-WmiObject -Class Win32_LogicalDiskToPartition

    Antecedent : \\computer\root\cimv2:Win32_DiskPartition.DeviceID="Disk #0, Partition #1"

    Dependent : \\computer\root\cimv2:Win32_LogicalDisk.DeviceID="D:"

    Just parse these two properties and filter the the other classes appropriately.