Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

USB Device Connected

Tags:

c#

c#-4.0

usb

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
}
like image 736
Robert Avatar asked Sep 10 '10 14:09

Robert


People also ask

What is connected device in USB?

Your USB cable plugs in here USB stands for Universal Serial Bus, an industry standard for short-distance digital data communications. USB ports allow USB devices to be connected to each other with and transfer digital data over USB cables. They can also supply electric power across the cable to devices that need it.


2 Answers

//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;
}
like image 179
Robert Avatar answered Oct 02 '22 06:10

Robert


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

like image 31
Dan H Avatar answered Oct 02 '22 05:10

Dan H