How to detect hard drives

  • Thread starter Thread starter Flix
  • Start date Start date
F

Flix

I need to detect the root directories of the installed hard disks (es: C:,
D:, E:, etc.). I'm not interested in cd drives.
I know that there is a way (a bit slow, if I remeber) to retrive all the
drives using a code like this:

ManagementClass diskClass = new ManagementClass("Win32_LogicalDisk");

ManagementObjectCollection disks = diskClass.GetInstances();

foreach (ManagementObject disk in disks) {

Console.WriteLine("Disk = " + disk["deviceid"]);

}

But I need only hard drives.
 
I need to detect the root directories of the installed hard
disks (es: C:, D:, E:, etc.). I'm not interested in cd drives.
I know that there is a way (a bit slow, if I remeber) to retrive
all the drives using a code like this:

ManagementClass diskClass = new
ManagementClass("Win32_LogicalDisk");

ManagementObjectCollection disks = diskClass.GetInstances();

foreach (ManagementObject disk in disks) {

Console.WriteLine("Disk = " + disk["deviceid"]);

}

But I need only hard drives.

Flix,

You can use the System.Environment.GetLogicalDrives method to get all
of the drives on your system, and then use an API call to
GetDriveType to filter out the hard drives.

// From Winbase.h
public enum DriveType : int
{
Unknown = 0,
NoRoot = 1,
Removable = 2,
Localdisk = 3,
Network = 4,
CD = 5,
RAMDrive = 6
}

[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
public static extern int GetDriveType(string lpRootPathName);

// Example usage:
using System;
....
foreach (string s in Environment.GetLogicalDrives())
Console.WriteLine(string.Format("Drive {0} is a {1}.",
s, Enum.GetName(typeof(DriveType), GetDriveType(s))));
 
Flix said:
I need to detect the root directories of the installed hard disks (es: C:,
D:, E:, etc.). I'm not interested in cd drives.

using System;
using System.Management;

string query = "select name from win32_logicaldisk where drivetype=3";
ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
foreach(ManagementObject manobj in searcher.Get()) {
// Do Something
}
 
Back
Top