【问题标题】:GET USB unique ID on putting or removing the key在放置或移除密钥时获取 USB 唯一 ID
【发布时间】:2011-06-07 12:41:53
【问题描述】:

在插入/移除 USB 时,我需要获取唯一的 USB ID(不是卷序列号)。但在所有情况下,“PNPDeviceID”始终为空。 我使用的代码是:

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

我可以使用以下代码获取唯一的 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)

【问题讨论】:

    标签: c# usb wmi wmi-query


    【解决方案1】:

    如果您直接查询Win32_LogicalDisk 类并且您没有获得PNPDeviceID 属性的值,那么当您在wmi 事件中使用该类时您也不会获得值。相反,您可以将 Win32_DiskDrive 类与 __InstanceOperationEvent 内在事件一起使用。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-08-04
      • 1970-01-01
      • 1970-01-01
      • 2010-10-11
      • 1970-01-01
      • 2015-12-23
      • 1970-01-01
      • 2021-01-15
      相关资源
      最近更新 更多