您可以ManagementObjectSearcher
利用它来查询USB的磁盘驱动器,然后获取相应的单元号并仅返回DriveInfo
结果RootDirectory.Name
集中包含的单元号。
使用 LINQ 查询表达式:
static IEnumerable<DriveInfo> GetUsbDevices()
{
IEnumerable<string> usbDrivesLetters = from drive in new ManagementObjectSearcher("select * from Win32_DiskDrive WHERE InterfaceType='USB'").Get().Cast<ManagementObject>()
from o in drive.GetRelated("Win32_DiskPartition").Cast<ManagementObject>()
from i in o.GetRelated("Win32_LogicalDisk").Cast<ManagementObject>()
select string.Format("{0}\\", i["Name"]);
return from drive in DriveInfo.GetDrives()
where drive.DriveType == DriveType.Removable && usbDrivesLetters.Contains(drive.RootDirectory.Name)
select drive;
}
使用 LINQ 扩展方法:
static IEnumerable<DriveInfo> GetUsbDevices()
{
IEnumerable<string> usbDrivesLetters = new ManagementObjectSearcher("select * from Win32_DiskDrive WHERE InterfaceType='USB'").Get().Cast<ManagementObject>()
.SelectMany(drive => drive.GetRelated("Win32_DiskPartition").Cast<ManagementObject>())
.SelectMany(o => o.GetRelated("Win32_LogicalDisk").Cast<ManagementObject>())
.Select(i => Convert.ToString(i["Name"]) + "\\");
return DriveInfo.GetDrives().Where(drive => drive.DriveType == DriveType.Removable && usbDrivesLetters.Contains(drive.RootDirectory.Name));
}
使用 foreach:
static IEnumerable<string> GetUsbDrivesLetters()
{
foreach (ManagementObject drive in new ManagementObjectSearcher("select * from Win32_DiskDrive WHERE InterfaceType='USB'").Get())
foreach (ManagementObject o in drive.GetRelated("Win32_DiskPartition"))
foreach (ManagementObject i in o.GetRelated("Win32_LogicalDisk"))
yield return string.Format("{0}\\", i["Name"]);
}
static IEnumerable<DriveInfo> GetUsbDevices()
{
IEnumerable<string> usbDrivesLetters = GetUsbDrivesLetters();
foreach (DriveInfo drive in DriveInfo.GetDrives())
if (drive.DriveType == DriveType.Removable && usbDrivesLetters.Contains(drive.RootDirectory.Name))
yield return drive;
}
要使用ManagementObject
,您需要添加对System.Management
我没有很好地测试它,因为我现在没有任何SD卡,但我希望它有所帮助