如何查找USB驱动器盘符?

Sum*_*rak 14 .net usb

我正在编写一个安装程序来将应用程序安装到USB驱动器上.该应用程序仅用于USB驱动器,因此可以通过自动选择要安装的USB驱动器为用户节省额外的步骤.

我可能会探索使用Nullsoft或MSI进行安装,但由于我最熟悉.NET,因此我最初计划在.NET上尝试自定义.NET安装程序或安装程序组件.

是否可以使用.NET在Windows上确定USB闪存驱动器的驱动器号?怎么样?

Ken*_*art 17

你可以使用:

from driveInfo in DriveInfo.GetDrives()
where driveInfo.DriveType == DriveType.Removable && driveInfo.IsReady
select driveInfo.RootDirectory.FullName
Run Code Online (Sandbox Code Playgroud)


GEO*_*HET 15

这将枚举没有LINQ但仍使用WMI的系统上的所有驱动器:

// browse all USB WMI physical disks

foreach(ManagementObject drive in new ManagementObjectSearcher(
    "select * from Win32_DiskDrive where InterfaceType='USB'").Get())
{
    // associate physical disks with partitions

    foreach(ManagementObject partition in new ManagementObjectSearcher(
        "ASSOCIATORS OF {Win32_DiskDrive.DeviceID='" + drive["DeviceID"]
          + "'} WHERE AssocClass = 
                Win32_DiskDriveToDiskPartition").Get())
    {
        Console.WriteLine("Partition=" + partition["Name"]);

        // associate partitions with logical disks (drive letter volumes)

        foreach(ManagementObject disk in new ManagementObjectSearcher(
            "ASSOCIATORS OF {Win32_DiskPartition.DeviceID='"
              + partition["DeviceID"]
              + "'} WHERE AssocClass =
                Win32_LogicalDiskToPartition").Get())
        {
            Console.WriteLine("Disk=" + disk["Name"]);
        }
    }

    // this may display nothing if the physical disk

    // does not have a hardware serial number

    Console.WriteLine("Serial="
     + new ManagementObject("Win32_PhysicalMedia.Tag='"
     + drive["DeviceID"] + "'")["SerialNumber"]);
}
Run Code Online (Sandbox Code Playgroud)

资源


Eri*_*fer 14

肯特代码的C#2.0版本(从我的头顶,未经测试):

IList<String> fullNames = new List<String>();
foreach (DriveInfo driveInfo in DriveInfo.GetDrives()) {
    if (driveInfo.DriveType == DriveType.Removable) {
        fullNames.Add(driveInfo.RootDirectory.FullName);
    }
}
Run Code Online (Sandbox Code Playgroud)