List USB devices in C#


[USB devices]

This program uses WMI (Windows Management Instrumentation) to query for USB devices. To use WMI, add a references to System.Management and add a using System.Management directive.

When it starts, this example uses the following code to list USB devices.

// Add a reference to System.Management.
using System.Management;
...
private void Form1_Load(object sender, EventArgs e)
{
    ManagementObjectSearcher device_searcher = 
        new ManagementObjectSearcher("SELECT * FROM Win32_USBHub");
    foreach (ManagementObject usb_device in device_searcher.Get())
    {
        ListViewItem new_item = lvwDevices.Items.Add(
            usb_device.Properties["DeviceID"].Value.ToString());
        new_item.SubItems.Add(
            usb_device.Properties["PNPDeviceID"].Value.ToString());
        new_item.SubItems.Add(
            usb_device.Properties["Description"].Value.ToString());
    }
}

This code creates a ManagementObjectSearcher to execute the WMI query SELECT * FROM Win32_USBHub. It then loops through the results displaying each USB device’s plug and play ID and description.

For more information on the Win32_PnPEntity class, see its Microsoft web page.

Unfortunately I haven’t figured out how to tell if a device is present and available for use. If you figure it out, post a comment below.


Download Example   Follow me on Twitter   RSS feed   Donate




This entry was posted in system and tagged , , , , , , , . Bookmark the permalink.

One Response to List USB devices in C#

  1. For what it’s worth, Win32_PnPEntity has a “Present” flag, but it is not supported.

    Indeed, when I turn my printer off (or unplug it), the Win32_PnPEntity representing the Printer disappears altogether, but the Win32_PnPEntity representing the PrintQueue remains.

    If I had to program an “offline” detector, I’d check whether the PrintQueue had a matching Printer. My suspicion (and this is hard to check unless you have two printers handy…I did a little while ago) is that if you just have one PrintQueue and one Printer, they match…and if you have multiple, they should have USB001 or USB002 or such in their device ids….

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.