Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get List of connected USB Devices

Tags:

c#

usb

How can I get a list of all the connected USB devices on a windows computer?

like image 988
Robert Avatar asked Jul 25 '10 21:07

Robert


People also ask

Can I see a history of USB devices on my computer?

If you don't know the name of your computer, go to Settings > System > About. Your computer name is shown at the top. Click the Start button to see the USB history. You can then expand the results to see details such as the time and date it was last used.

Where are USB devices in Linux?

In Linux, all device files are stored in /dev directory and must be available to the OS during the system boot. In this guide, we will show you the various ways to list USB devices on Linux. Most commands mentioned here should work on all Linux distributions.

How do I find USB devices on Windows 11?

Once you are in Device Manager -> Expand the Disk Drives, then Right-click on the USB SanDisk 3.2Gen1 USB Device and goto properties to get the USB Drive Hardware ID on Windows 11 device.


2 Answers

Add a reference to System.Management for your project, then try something like this:

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; }   } } 
like image 70
Adel Hazzah Avatar answered Oct 01 '22 12:10

Adel Hazzah


I know I'm replying to an old question, but I just went through this same exercise and found out a bit more information, that I think will contribute a lot to the discussion and help out anyone else who finds this question and sees where the existing answers fall short.

The accepted answer is close, and can be corrected using Nedko's comment to it. A more detailed understanding of the WMI Classes involved helps complete the picture.

Win32_USBHub returns only USB Hubs. That seems obvious in hindsight but the discussion above misses it. It does not include all possible USB devices, only those which can (in theory, at least) act as a hub for additional devices. It misses some devices that are not hubs (particularly parts of composite devices).

Win32_PnPEntity does include all the USB devices, and hundreds more non-USB devices. Russel Gantman's advice to use a WHERE clause search Win32_PnPEntity for a DeviceID beginning with "USB%" to filter the list is helpful but slightly incomplete; it misses bluetooth devices, some printers/print servers, and HID-compliant mice and keyboards. I have seen "USB\%", "USBSTOR\%", "USBPRINT\%", "BTH\%", "SWD\%", and "HID\%". Win32_PnPEntity is, however, a good "master" reference to look up information once you are in possession of the PNPDeviceID from other sources.

What I found was the best way to enumerate USB devices was to query Win32_USBControllerDevice. While it doesn't give detailed information for the devices, it does completely enumerate your USB devices and gives you an Antecedent/Dependent pair of PNPDeviceIDs for every USB Device (including Hubs, non-Hub devices, and HID-compliant devices) on your system. Each Dependent returned from the query will be a USB Device. The Antecedent will be the Controller it is assigned to, one of the USB Controllers returned by querying Win32_USBController.

As a bonus, it appears that under the hood, WMI walks the Device Tree when responding to the Win32_USBControllerDevice query, so the order in which these results are returned can help identify parent/child relationships. (This is not documented and is thus only a guess; use the SetupDi API's CM_Get_Parent (or Child + Sibling) for definitive results.) As an option to the SetupDi API, it appears that for all the devices listed under Win32_USBHub they can be looked up in the registry (at HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Enum\ + PNPDeviceID) and will have a parameter ParentIdPrefix which will be the prefix of the last field in the PNPDeviceID of its children, so this could also be used in a wildcard match to filter the Win32_PnPEntity query.

In my application, I did the following:

  • (Optional) Queried Win32_PnPEntity and stored the results in a key-value map (with PNPDeviceID as the key) for later retrieval. This is optional if you want to do individual queries later.
  • Queried Win32_USBControllerDevice for a definitive list of USB devices on my system (all the Dependents) and extracted the PNPDeviceIDs of these. I went further, based on order following the device tree, to assign devices to the root hub (the first device returned, rather than the controller) and built a tree based on the parentIdPrefix. The order the query returns, which matches device tree enumeration via SetupDi, is each root hub (for whom the Antecedent identifies the controller), followed by an iteration of devices under it, e.g., on my system:
    • Root hub of first controller
    • Root hub of second controller
      • First hub under root hub of second controller (has parentIdPrefix)
        • First composite device under first hub under root hub of second controller (PNPDeviceID matches above hub's ParentIdPrefix; has its own ParentIdPrefix)
          • HID Device part of the composite device (PNPDeviceID matches above composite device's ParentIDPrefix)
        • Second device under first hub under root hub of second controller
          • HID Device part of the composite device
      • Second hub under root hub of second controller
        • First device under second hub under root hub of second controller
      • Third hub under root hub of second controller
      • etc.
  • Queried Win32_USBController. This gave me the detailed information of the PNPDeviceIDs of my controllers which are at the top of the device tree (which were the Antecedents of the previous query). Using the tree derived in the previous step, recursively iterated over its children (the root hubs) and their children (the other hubs) and their children (non-hub devices and composite devices) and their children, etc.
    • Retrieved details for each device in my tree by referencing the map stored in the first step. (Optionally, one could skip the first step, and query Win32_PnPEntity individually using the PNPDeviceId to get the information at this step; probably a cpu vs. memory tradeoff determining which order is better.)

In summary, Win32USBControllerDevice Dependents are a complete list of USB Devices on a system (other than the Controllers themselves, which are the Antecedents in that same query), and by cross-referencing these PNPDeviceId pairs with information from the registry and from the other queries mentioned, a detailed picture can be constructed.

like image 43
Daniel Widdis Avatar answered Oct 01 '22 11:10

Daniel Widdis