如何查找USB驱动器盘符?

时间:2008-09-23 21:15:14

标签: .net usb

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

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

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

3 个答案:

答案 0 :(得分:17)

您可以使用:

from driveInfo in DriveInfo.GetDrives()
where driveInfo.DriveType == DriveType.Removable && driveInfo.IsReady
select driveInfo.RootDirectory.FullName

答案 1 :(得分: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"]);
}

Source

答案 2 :(得分: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);
    }
}