Pergunta

When I open Disk Management (right click My Computer->Manage) I see: enter image description here

How can I know that path F:\ belongs to Disk5? In other words I will like to know what disks are available with C#.

The reason why I need to know that is because I have a usb mas storage device that is encrypted and I need to pass the parameter \Device\Harddisk5 to TrueCrypt along with the password in order to mount the encrypted device with code.

Edit

I know how to look the drives info. I just dont konw how to know that Drive 1 belongs to disk 0 for instance. In other words I am having trouble figuring out the Disk Number. I am looking to implement:

public string GetDiskNumber(char letter)
{
   // implenetation
   return Disk5;
}

where I will call that as:

GetDiskNumber('F');
Foi útil?

Solução

You can use WMI to retrieve that information

System.Management.ManagementObject("Win32_LogicalDisk.DeviceID=" & DriveLetter & ":")

See more at Win32_LogicalDisk class I hope it helps. By the way there is PInvoke too GetVolumeInformation.

If you need 'PHYSICALDRIVE0' you should use Win32_PhysicalMedia class and the class Win32_DiskDrivePhysicalMedia glue both.

An exemple of your need in C#

public string GetDiskNumber(string letter)
{
    var ret = "0";
    var scope = new ManagementScope("\\\\.\\ROOT\\cimv2");
    var query = new ObjectQuery("Associators of {Win32_LogicalDisk.DeviceID='" +     letter + ":'} WHERE ResultRole=Antecedent");
    var searcher = new ManagementObjectSearcher(scope, query);
    var queryCollection = searcher.Get();
    foreach (ManagementObject m in queryCollection)
    {
        ret = m["Name"].ToString().Replace("Disk #", "")[0].ToString();
    }
    return ret;
}

Outras dicas

Have made a method for you gets drive letter and its number in a dictionary;

public Dictionary<string, string> GetDrives()
        {
            var result = new Dictionary<string, string>();
            foreach ( var drive in new ManagementObjectSearcher( "Select * from Win32_LogicalDiskToPartition" ).Get().Cast<ManagementObject>().ToList() )
            {
                var driveLetter = Regex.Match( (string)drive[ "Dependent" ], @"DeviceID=""(.*)""" ).Groups[ 1 ].Value;
                var driveNumber = Regex.Match( (string)drive[ "Antecedent" ], @"Disk #(\d*)," ).Groups[ 1 ].Value;
                result.Add( driveLetter, driveNumber );
            }
            return result;
        }
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top