USB Device Connected

11,409

Solution 1

//using System.Management
public bool IsUsbDeviceConnected(string pid, string vid)
{   
  using (var searcher = 
    new ManagementObjectSearcher(@"Select * From Win32_USBControllerDevice"))
  {
    using (var collection = searcher.Get())
    {
      foreach (var device in collection)
      {
        var usbDevice = Convert.ToString(device);

        if (usbDevice.Contains(pid) && usbDevice.Contains(vid))
          return true;
      }
    }
  }
  return false;
}

Solution 2

may be something like

//import the System.Management namespace at the top in your "using" statement. Then in a method, or on a button click:

ManagementObjectCollection collection;
using (ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_DiskDrive WHERE InterfaceType='USB'"))
  collection = searcher.Get();
foreach (ManagementObject currentObject in collection)
{
  ManagementObject theSerialNumberObjectQuery = new ManagementObject("Win32_PhysicalMedia.Tag='" + currentObject["DeviceID"] + "'");
  MessageBox.Show(theSerialNumberObjectQuery["SerialNumber"].ToString());
}
collection.Dispose();

Using WMI

Share:
11,409
Robert
Author by

Robert

Updated on June 17, 2022

Comments

  • Robert
    Robert almost 2 years

    I'm trying to make a function that detects if a usb device is connected given the devices pid and vid. I'm hoping it would look something like this, I'm just not sure how to do this in C#.

    public bool IsUsbDeviceConnected(string pid, string vid)
    {
      //Code here
    }
    
  • Robert
    Robert over 13 years
    I don't have a serial number, only the vendor id and product id which is nested somewhere in the usb. Also that WMI call looks for Win32_DiskDrives, not all USB devices.
  • Shimmy Weitzhandler
    Shimmy Weitzhandler over 12 years
    Can you please help me out with this related question?