C# USB 闪存 PNPDeviceID 在某些系统上不同

C# USB flash PNPDeviceID different on some systems

我正在尝试使用此代码获取 USB 闪存驱动器 ID:

ManagementObjectSearcher theSearcher = new ManagementObjectSearcher("SELECT * FROM Win32_DiskDrive WHERE InterfaceType='USB'");
foreach (ManagementObject currentObject in theSearcher.Get())
{                    
    Console.WriteLine("PNPDeviceID: " + currentObject["PNPDeviceID"]);                    
}

在大多数计算机上,我会得到这样的信息:USBSTOR\DISK&VEN_TQ&PROD_S1&REV_1.10100049977&0

但是在同一 USB 驱动器的某些系统上,我得到如下信息: USBSTOR\DISK&VEN_TQ&PROD_S1&REV_1.10\ 6&2D2B8A01&0& 11100049977&0

请注意,6&2D2B8A01&0& 部分会根据 USB 驱动器插入的端口而变化。

无论 USB 驱动器插入哪个端口,如何在每个系统上获取 ID 的第一个版本?

更新 1:当使用 Win32_DiskDrive 每台 PC 上都检测到 USB 驱动器。但是当使用 Win32_USBHub 有问题的 PC 上未检测到 USB 驱动器时。

更新 2:当使用此 中的 SystemUSBDrives class 时,在有问题的 PC 上我得到以下输出:

端口 1:

SystemUSBDrives PNPDeviceID: USBSTOR\DISK&VEN_TQ&PROD_S1&REV_1.10&2D2B8A01&0&11100049977&0
SystemUSBDrives DeviceID: \.\PHYSICALDRIVE2
SystemUSBDrives SerialNumber:  
SystemUSBDrives VolumeSerialNumber: D6533504

端口 2:

SystemUSBDrives PNPDeviceID: USBSTOR\DISK&VEN_TQ&PROD_S1&REV_1.10&7A722D3&0&11100049977&0
SystemUSBDrives DeviceID: \.\PHYSICALDRIVE2
SystemUSBDrives SerialNumber:  
SystemUSBDrives VolumeSerialNumber: D6533504

端口 3:

SystemUSBDrives PNPDeviceID: USBSTOR\DISK&VEN_TQ&PROD_S1&REV_1.10&32CECE73&0&11100049977&0
SystemUSBDrives DeviceID: \.\PHYSICALDRIVE2
SystemUSBDrives SerialNumber:  
SystemUSBDrives VolumeSerialNumber: D6533504

在其他计算机上使用此 returns 正确的 SystemUSBDrives SerialNumber 值。

使用 DriveInfo 您可以获得所有驱动程序信息。

看这里DriveType

 var drivers = DriveInfo.GetDrives() //all Drivers
                    .Where(x => x.DriveType == DriveType.Removable); //Filter Removable Drivers

或者如果您需要 PNPDeviceID

var deviceSearcher =
            new ManagementObjectSearcher("SELECT * FROM Win32_USBHub");
        foreach (var o in deviceSearcher.Get())
        {
            var usbDevice = (ManagementObject)o;
            var pnpDeviceId = usbDevice.Properties["PNPDeviceID"].Value.ToString();
        }

我最终从字符串中删除了 ParentIdPrefix,它适用于我的场景:

public static string RemoveParentIdPrefix(string pnpDeviceId)
{
    int iSplit = pnpDeviceId.LastIndexOf("\", StringComparison.InvariantCulture);
    string part1 = pnpDeviceId.Substring(0, iSplit);
    string part2 = pnpDeviceId.Substring(iSplit);
    int ampersandCount = 0;
    for (int i = part2.Length - 1; i >= 0; i--)
    {
        if (part2[i] == '&')
        {
            ampersandCount++;
        }

        if (ampersandCount == 2)
        {
            part2 = part2.Substring(i + 1);
            break;
        }
    }
    return part1 + "\" + part2;
}