开发者

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

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开发者_Go百科 a start.


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.)


You can cycle through all drives and check the Name and VolumeLabel properties of DriveInfo object.

See this question for code examples (used to get the USB drive letter, but you can easily adapt it):

How to find USB drive letter?

Sorry I cannot provide you some code, but I'm on a Mac right now :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜