C# how to know if removable disk is a usb drive, or a sd card?

前端 未结 2 1568
野的像风
野的像风 2021-02-19 04:55

Windows 7 platform, C#

I use the following statement to list all drives:

DriveInfo[] drives = DriveInfo.GetDrives();

then I can use Dri

2条回答
  •  星月不相逢
    2021-02-19 05:38

    You can take advantage of ManagementObjectSearcher using it to query the disk drives that are USB, then obtain the corresponding unit letter and return only the DriveInfo of which RootDirectory.Name is contained in the result set.

    Using LINQ Query Expressions:

    static IEnumerable GetUsbDevices()
    {
        IEnumerable usbDrivesLetters = from drive in new ManagementObjectSearcher("select * from Win32_DiskDrive WHERE InterfaceType='USB'").Get().Cast()
                                               from o in drive.GetRelated("Win32_DiskPartition").Cast()
                                               from i in o.GetRelated("Win32_LogicalDisk").Cast()
                                               select string.Format("{0}\\", i["Name"]);
    
        return from drive in DriveInfo.GetDrives()
               where drive.DriveType == DriveType.Removable && usbDrivesLetters.Contains(drive.RootDirectory.Name)
               select drive;
    }
    

    Using LINQ Extension Methods:

    static IEnumerable GetUsbDevices()
    {
        IEnumerable usbDrivesLetters = new ManagementObjectSearcher("select * from Win32_DiskDrive WHERE InterfaceType='USB'").Get().Cast()
            .SelectMany(drive => drive.GetRelated("Win32_DiskPartition").Cast())
            .SelectMany(o => o.GetRelated("Win32_LogicalDisk").Cast())
            .Select(i => Convert.ToString(i["Name"]) + "\\");
    
        return DriveInfo.GetDrives().Where(drive => drive.DriveType == DriveType.Removable && usbDrivesLetters.Contains(drive.RootDirectory.Name));
    }
    

    Using foreach:

    static IEnumerable 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 GetUsbDevices()
    {
        IEnumerable usbDrivesLetters = GetUsbDrivesLetters();
        foreach (DriveInfo drive in DriveInfo.GetDrives())
            if (drive.DriveType == DriveType.Removable && usbDrivesLetters.Contains(drive.RootDirectory.Name))
                yield return drive;
    }
    

    To use ManagementObject you need to add reference to System.Management

    I haven't tested it well because now I don't have any SD card, but I hope it helps

提交回复
热议问题