7

I need to get the unique USB ID (not a Volume serial number ) on putting/removing the USB. But in all case "PNPDeviceID" is always empty. The code which I used is:

static void Main(string[] args)
{ 
    const string QUERY = @"select * from __InstanceOperationEvent within 1 where TargetInstance isa 'Win32_LogicalDisk' and (TargetInstance.DriveType=2)"; 
    Program p = new Program(); 
    ManagementEventWatcher w = new ManagementEventWatcher(new WqlEventQuery(QUERY));
    w.EventArrived += new EventArrivedEventHandler(p.OnWMIEvent); 
    w.Start();
    Console.ReadKey();
    w.Stop();
}

public void OnWMIEvent(object sender, EventArrivedEventArgs e)
{
    PropertyData p = e.NewEvent.Properties["TargetInstance"]; 
    if (p != null) 
    {
        ManagementBaseObject mbo = p.Value as ManagementBaseObject;
        PropertyData deviceid = mbo.Properties["DeviceID"]; 
        PropertyData drivetype = mbo.Properties["DriveType"];
        PropertyData driveSerial = mbo.Properties["VolumeSerialNumber"];
        PropertyData driveGUID = mbo.Properties["PNPDeviceID"];

        Console.WriteLine("{0}-{1}", "DeviceID",deviceid.Value); 
        Console.WriteLine("{0}-{1}", "DriveType",drivetype.Value);
        Console.WriteLine("{0}-{1}", "DriveSerial", driveSerial.Value);
        Console.WriteLine("{0}-{1}", "driveGUID", driveGUID.Value);
        Console.WriteLine();
    }
} 

Source is:this

I Can get the UNIQUE USB id with the following code:

ManagementObjectSearcher theSearcher = 
    new ManagementObjectSearcher("SELECT * FROM Win32_DiskDrive WHERE InterfaceType='USB'");

foreach(ManagementObject currentObject in theSearcher.Get())
{
    Console.WriteLine("{0}-{1}", "PNPDeviceID", currentObject.Properties["PNPDeviceID"].Value);            
}

So please can you tell me how can I combine them to receive PNPDeviceId (USB GUID) when I put/remove the USB stick

Community
  • 1
  • 1
Tiho
  • 123
  • 2
  • 8

1 Answers1

2

If you query directly the Win32_LogicalDisk class and you don't get values for the PNPDeviceID property, neither you will get values when you use this class inside of the wmi event. instead you can use the Win32_DiskDrive class with the __InstanceOperationEvent intrinsic event.

Select * From __InstanceOperationEvent Within 1 Where TargetInstance ISA 'Win32_DiskDrive' and TargetInstance.InterfaceType='USB'
RRUZ
  • 134,889
  • 20
  • 356
  • 483