C# 在放入或取出密钥时获取USB唯一ID
我需要在放置/移除USB时获得唯一的USB ID(不是卷序列号)。但无论如何,“PNPDeviceID”总是空的。 我使用的代码是:C# 在放入或取出密钥时获取USB唯一ID,c#,usb,wmi,wmi-query,C#,Usb,Wmi,Wmi Query,我需要在放置/移除USB时获得唯一的USB ID(不是卷序列号)。但无论如何,“PNPDeviceID”总是空的。 我使用的代码是: static void Main(string[] args) { const string QUERY = @"select * from __InstanceOperationEvent within 1 where TargetInstance isa 'Win32_LogicalDisk' and (TargetInstance.DriveTyp
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();
}
}
资料来源是:
我可以通过以下代码获得唯一的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);
}
因此,请您告诉我,当我放置/移除U盘时,如何组合它们以接收PNPDeviceId(USB GUID)如果您直接查询该类,并且没有获得PNPDeviceId属性的值,那么在wmi事件中使用该类时,您也不会获得值。相反,您可以将该类与\uu InstanceOperationEvent
内部事件一起使用
Select * From __InstanceOperationEvent Within 1 Where TargetInstance ISA 'Win32_DiskDrive' and TargetInstance.InterfaceType='USB'