Search code examples
c#usbwmiwmi-querydevice-manager

How to read WMI data of a USB (PnP) device, in this case the hardware ids, in C#?


How can I get the hardware id from an USB device? I know how to get that id with device-manager, but I want to get it via C#. Is that possible? This is what I´ve done already, but that delivers me not the hardware if which consists of the vendor id (VID) and the product id (PID):

ManagementObjectSearcher USB = new ManagementObjectSearcher("SELECT * FROM Win32_DiskDrive WHERE InterfaceType='USB'");
ManagementObjectCollection USBinfo = USB.Get();

foreach (ManagementObject MO in USBinfo)
{
    serialNumber = (string)MO["DeviceID"];
    name = (string)MO["Name"];
    Drives.Add(new KeyValuePair<String, String>(name, serialNumber));
}

I also tried it with "PNPDeviceID" and "SerialNumber" instead of "DeviceID", but that also doesn´t replys the hardware-id that I need.


Solution

  • In Console application, add refrence-->.Net-->system.Management-->add

    namespace ConsoleApplication1
    {
      using System;
      using System.Collections.Generic;
      using System.Management; // need to add System.Management to your project references.
    
      class Program
      {
        static void Main(string[] args)
        {
          var usbDevices = GetUSBDevices();
    
          foreach (var usbDevice in usbDevices)
          {
            Console.WriteLine("Device ID: {0}, PNP Device ID: {1}, Description: {2}",
                usbDevice.DeviceID, usbDevice.PnpDeviceID, usbDevice.Description);
          }
    
          Console.Read();
        }
    
        static List<USBDeviceInfo> GetUSBDevices()
        {
          List<USBDeviceInfo> devices = new List<USBDeviceInfo>();
          ManagementObjectCollection collection;
    
          using (var searcher = new ManagementObjectSearcher(@"Select * From Win32_USBHub"))
            collection = searcher.Get();      
    
          foreach (var device in collection)
          {
            devices.Add(new USBDeviceInfo(
            (string)device.GetPropertyValue("DeviceID"),
            (string)device.GetPropertyValue("PNPDeviceID"),
            (string)device.GetPropertyValue("Description")
            ));
          }
    
          collection.Dispose();
          return devices;
        }
      }
    
      class USBDeviceInfo
      {
        public USBDeviceInfo(string deviceID, string pnpDeviceID, string description)
        {
          this.DeviceID = deviceID;
          this.PnpDeviceID = pnpDeviceID;
          this.Description = description;
        }
    
        public string DeviceID { get; private set; }
        public string PnpDeviceID { get; private set; }
        public string Description { get; private set; }
      }
    }