开发者

GET USB unique ID on putting or removing the key

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 = 
    ne开发者_如何学运维w 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


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'
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜