繁体   English   中英

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.10 \\ 11100049977&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类时,在有问题的PC上,我得到以下输出:

端口1:

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

端口2:

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

端口3:

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

在其他计算机上使用此命令将返回正确的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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM