3
votes

I have a device that connects to the computer through serial port. I understand to open the port in .NET I can call the port by COM number. For example

SerialPort s = new SerialPort("COM9");
s.Open();

calls the device on COM9. However, if I run my program and serial port device on another computer port number could be changed, yet the device name is always the same on every computer. For example in this picture I would like to communicate with "Numato Lab 8 Channel USB Relay Module" regardless of the COM port number (Name is always the same as opposed to the port number).

enter image description here

Question is: Is there anyway that instead of the code above I call my device with its name as shown in device manager rather than its port number? like

SerialPort s = new SerialPort("Numato Lab 8 Channel USB Relay Module");
1
Possible duplicate of Getting Serial Port InformationJohnny Mopp

1 Answers

3
votes

You have to access WMI to get that information. You can use ORMi library for easy access:

Just create a class:

[WMIClass("Win32_PnPEntity")]
public class Device
{
    public string Caption { get; set;}
}

Then query:

WMIHelper helper = new WMIHelper("root\\CimV2");

Device device = helper.Query<Device>().ToList().Where(p => p.Caption == "Numato Lab 8 Channel USB Relay Module").SingleOrDefault();

If you want to get more information, then add more properties to the Device class. Properties should match WMI specification for Win32_PnPEntity class.

Once you got the device you might have to also query Win32_SerialPort class to know on what port your device is connected. I leave that to your investigation.

Here you got a large explanation if you want to do all the work yourself:

https://codereview.stackexchange.com/questions/111178/find-a-serial-port-device-through-wmi-windows-management-instrumentation