2011-06-07 37 views
7

我需要得到把/移除USB獨特的USB ID(而不是卷序列號)USB唯一的ID。但在所有情況下,「PNPDeviceID」始終爲空。 這是我使用的代碼是:GET上投入或取出鑰匙

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(); 
    } 
} 

來源是:this

我可以得到下面的代碼UNIQUE USB ID:

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);    
} 

所以,請你能告訴我怎麼能我結合他們接受PNPDeviceId(USB GUID)當我把/刪除USB棒

回答

2

如果查詢直接Win32_LogicalDiskç姑娘,你不爲PNPDeviceID屬性獲取值,既不當您使用WMI事件內這個類,你會得到的值。相反,您可以使用Win32_DiskDrive類與__InstanceOperationEvent內部事件。

Select * From __InstanceOperationEvent Within 1 Where TargetInstance ISA 'Win32_DiskDrive' and TargetInstance.InterfaceType='USB'