C#如何知道可移动磁盘是USB驱动器还是SD卡?

标签 c# removable

Windows 7 平台,C#

我使用以下语句列出所有驱动器:

DriveInfo[] drives = DriveInfo.GetDrives();

然后我可以使用 DriveType 找出所有那些可移动磁盘:

foreach (var drive in drives)
{
     if(drive.DriveType == DriveType.Removable)
         yield return drive;
}

现在我的问题是,SD卡盘和U盘共享同一个driveType: Removable,那我怎么只能找到U盘呢?

谢谢!

最佳答案

可以利用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 卡,但我希望它对您有所帮助

关于C#如何知道可移动磁盘是USB驱动器还是SD卡?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31559121/

相关文章:

delphi - 如何查找闪存设备的唯一序列号?

delphi - 始终检测可移动设备的最佳方法

linux - 在 Linux 中检测 USB 大容量存储弹出/卸载

c# - 从 URL 中隐藏 default.aspx

c# - 应用程序设置界面

c# - 如何决定 Office 365 上的退回电子邮件?

c# - 在 ScrollView 中滚动到选定的 Treeviewitem

c# - .NET 4.0 项目无法在 Windows xp 上运行