Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

See disk management info with c#

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');
like image 662
Tono Nam Avatar asked Mar 21 '23 20:03

Tono Nam


1 Answers

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;
}
like image 54
gblmarquez Avatar answered Apr 02 '23 09:04

gblmarquez