windows 如何从驱动器的全名中获取驱动器号

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7222782/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 17:57:02  来源:igfitidea点击:

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

c#.netwindowsfileinfodrive-letter

提问by James

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?

如何在 Windows 下使用 C# 从驱动器(例如 WORKMEMORYSTICK)的已知全名(如果存在)获取驱动器号(例如 F:\)?

Even the other way around would be a start.

即使反过来也将是一个开始。

采纳答案by Grant Thomas

The DriveInfoclass 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:

DriveInfo类公开的方法来获取所有可用的驱动器(GetDrives),你可以enyumerate这些的比赛你指定的字符串。类似以下内容应该可以帮助您到达那里:

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

正如 abatishchev 所提到的,由于我孩子的时间要求,最初没有详细说明,存在一个潜在的问题,即您只会匹配具有该标签的第一个驱动器,因此您需要在如果您的系统需要,您的逻辑(不过,根据非唯一字符串确定两个驱动器中哪一个是所需的驱动器并不比猜测好,或者正如我在下面提到的,询问用户(如果这是输入)他们指的是哪一个。)

回答by mamoo

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

您可以循环浏览所有驱动器并检查DriveInfo 对象的 Name 和 VolumeLabel属性

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

有关代码示例,请参阅此问题(用于获取 USB 驱动器盘符,但您可以轻松调整它):

How to find USB drive letter?

如何找到USB驱动器号?

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

抱歉,我无法为您提供一些代码,但我现在使用的是 Mac :)