.net 如何找到USB驱动器号?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/123927/
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
How to find USB drive letter?
提问by Sumrak
I'm writing a setup program to install an application to a USB drive. The application is meant to be used only from USB drives, so it would save an extra step for the user by automatically selecting USB drive to install to.
我正在编写一个安装程序来将应用程序安装到 USB 驱动器。该应用程序仅适用于 USB 驱动器,因此通过自动选择要安装到的 USB 驱动器,可以为用户节省额外的步骤。
I might explore using Nullsoft or MSI for install, but since I'm mostly familiar with .NET I initially plan to try either custom .NET installer or setup component on .NET.
我可能会探索使用 Nullsoft 或 MSI 进行安装,但由于我最熟悉 .NET,因此我最初计划在 .NET 上尝试自定义 .NET 安装程序或安装组件。
Is it possible to determine the drive letter of a USB flash drive on Windows using .NET? How?
是否可以使用 .NET 在 Windows 上确定 USB 闪存驱动器的驱动器号?如何?
回答by Kent Boogaart
You could use:
你可以使用:
from driveInfo in DriveInfo.GetDrives()
where driveInfo.DriveType == DriveType.Removable && driveInfo.IsReady
select driveInfo.RootDirectory.FullName
回答by GEOCHET
This will enumerate all the drives on the system without LINQ but still using WMI:
这将枚举系统上没有 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"]);
}
回答by EricSchaefer
C# 2.0 version of Kent's code (from the top of my head, not tested):
C# 2.0 版本的 Kent 代码(来自我的头脑,未测试):
IList<String> fullNames = new List<String>();
foreach (DriveInfo driveInfo in DriveInfo.GetDrives()) {
if (driveInfo.DriveType == DriveType.Removable) {
fullNames.Add(driveInfo.RootDirectory.FullName);
}
}

