How to find usb devices in c #?

I need to iterate through the ports connected to the computer and find the specific device. Check out the image below:

enter image description here

You can see that there are 4 device names with the same vendor and product identifier. but I need to find the port of the first, which is highlighted in blue. it seems that the only difference they have is the name of the friend (description is the name of the friend).

What is the easiest way to achieve this in C # .net? I did this in "qt" and I need to know how to do this in C # ,. net framework 4 using vs 2010 professional. I went through issues such as, but, as you can see, they do not help my situation.

+6
source share
1 answer

If you are using libusbdotnet , you should do something like this:

public static void RetrieveUSBDevices(int vid, int pid) { var usbFinder = new UsbDeviceFinder(vid, pid); var usbDevices = new UsbRegDeviceList(); usbDevices = usbDevices.FindAll(usbFinder); } 

Then you can iterate through usbDevices and check the correct FullName . I did not check it, although it is theoretically.

UPDATE : Tried this and it worked perfectly - what's the problem? Why vote at the expense of your own incompetence?

This will also work:

 private static void Method() { var list = GetMyUSBDevices(); //Iterate list here and use Description to find exact device } private static List<UsbDevice> GetMyUSBDevices() { var vid = 32903; var pid = 36; ManagementObjectCollection collection; using (var searcher = new ManagementObjectSearcher(@"Select * From Win32_USBHub")) collection = searcher.Get(); var usbDevice = (from ManagementBaseObject device in collection select new UsbDevice( (string) device.GetPropertyValue("DeviceID"), (string) device.GetPropertyValue("Description"))).ToList(); var devices = new List<UsbDevice>(); foreach (var device in collection) { devices.Add(new UsbDevice( (string)device.GetPropertyValue("DeviceID"), (string)device.GetPropertyValue("Description") )); } collection.Dispose(); return (from d in devices where d.DeviceId.Contains("VID_") && d.DeviceId.Contains("PID_") && d.PID.Equals(pid) && d.VID.Equals(vid) select d).ToList(); } public class UsbDevice { public UsbDevice(string deviceId, string description) { DeviceId = deviceId; Description = description; } public string DeviceId { get; private set; } public string Description { get; private set; } public int VID { get { return int.Parse(GetIdentifierPart("VID_"), System.Globalization.NumberStyles.HexNumber); } } public int PID { get { return int.Parse(GetIdentifierPart("PID_"), System.Globalization.NumberStyles.HexNumber); } } private string GetIdentifierPart(string identifier) { var vidIndex = DeviceId.IndexOf(identifier, StringComparison.Ordinal); var startingAtVid = DeviceId.Substring(vidIndex + 4); return startingAtVid.Substring(0, 4); } } 
+8
source

Source: https://habr.com/ru/post/951598/


All Articles