Wednesday, March 11, 2009

Get All Physical Drives

.Net 2005 provides us with the DriveInfo Class which enables us to get all logical drives in our system. We can use this class along with the property of DriveType to filter out the physical drives. But the problem with this approach is, suppose you were to connect an external USB Hard disk to your system, even that is detected as Physical Drive. Ideally you would want that to be detected as a Removable Drive.

We can accomplish this using WMI Classes. Check out the following function

private static StringCollection GetDrives()
{
StringCollection drives = new StringCollection();

foreach(ManagementObject drive in new ManagementObjectSearcher("select * from Win32_DiskDrive where InterfaceType!='USB'").Get())
{
foreach(ManagementObject partition in new ManagementObjectSearcher("ASSOCIATORS OF {Win32_DiskDrive.DeviceID='" + drive["DeviceID"] + "'} WHERE AssocClass = Win32_DiskDriveToDiskPartition").Get())
{
foreach(ManagementObject disk in new ManagementObjectSearcher("ASSOCIATORS OF {Win32_DiskPartition.DeviceID='"+ partition["DeviceID"]+ "'} WHERE AssocClass = Win32_LogicalDiskToPartition").Get())
{
drives.Add(disk["Name"].ToString());
}
}
}
return drives;
}