How to get the drive letter from a full name of the drive

James picture James · Aug 28, 2011 · Viewed 9.5k times · Source

How could the drive letter (e.g. F:\) be obtained from a known full name (if it is present) of a drive (e.g. WORKMEMORYSTICK) using C# under Windows?

Even the other way around would be a start.

Answer

Grant Thomas picture Grant Thomas · Aug 28, 2011

The DriveInfo class exposes a method to get all available drives (GetDrives), you could enyumerate these an match your given string. Something like the following ought to help get you there:

DirectoryInfo root;
var drives = DriveInfo.GetDrives();
foreach (var drive in drives)
{
    if (drive.VolumeLabel == label)
    {
        root = drive.RootDirectory;
        break;
    }
}

As mentioned by abatishchev, and not initially elaborated on due to the time requirements of my children, there is a potential problem in that you're only going to match the first drive which has that label, therefore you will need to account for this in your logic if your system requires it (though, determining which of two drives is the desired drive based on nothing but a non-unique string is no better than a guess, or as I mention below, asking the user (if this is input) which one they meant.)