Reputation: 746
I have a USB device that provides a virtual com port. However this device does not identify itself by a COM port "friendly name" (in windows unit manager for instance).
However it does provide a proper name for the USB device. Which in turn lists the associated com port as follows:
I'd like to be able to identify the device by name ("Prologix GPIB...") and get the com port number from that name. How can i do this in C# / .NET?
The only code i was able to find only searched by the COM port friendly name, not the USB device name.
Thanks for your time!
Upvotes: 3
Views: 9979
Reputation: 3769
I don't have virtual COM port set up, so can't check this, but one of the answers in this article seems to fit your requirement:
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; }
}
This works fine for listing my devices. You may need to experiment with additional PropertyValue
fields in GetUSBDevices
to find virtual COM port names.
Upvotes: 4