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

喜欢而已 提交于 2019-12-24 01:06:42

问题


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.


回答1:


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




回答2:


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



来源:https://stackoverflow.com/questions/7222782/how-to-get-the-drive-letter-from-a-full-name-of-the-drive

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!