如何从驱动器全名获取驱动器号

发布于 2024-12-01 23:11:21 字数 97 浏览 1 评论 0原文

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

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

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

﹎☆浅夏丿初晴 2024-12-08 23:11:21

DriveInfo 类公开获取所有可用驱动器的方法(GetDrives),您可以枚举这些与给定字符串匹配的内容。像下面这样的东西应该可以帮助你到达那里:

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

正如 abatishchev 所提到的,由于我孩子的时间要求,最初没有详细说明,存在一个潜在的问题,因为你只会匹配 first< /em> 具有该标签的驱动器,因此,如果您的系统需要它,则需要在逻辑中考虑这一点(不过,确定两个驱动器中的哪一个是所需的驱动器仅基于非-唯一的字符串并不比猜测更好,或者作为我在下面提到,询问用户(如果这是输入)他们的意思是哪一个。)

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

痴骨ら 2024-12-08 23:11:21

您可以循环浏览所有驱动器并检查 DriveInfo 对象的名称和卷标签属性。

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

如何查找 USB 驱动器盘符?

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

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文