I'm currently working on a project using the SerialPort
class in C# to communicate with RS232-based calibration devices used at the company I work for. In the SerialPort class, there is a static method named GetPortNames()
.
Unfortunately, Windows has a terrible problem with keeping around stale port entries. If I call GetPortNames()
from my machine, it returns the following ports:
COM3
COM4
COM1
Of these ports, only one physically exists right now. I have a PCIe RS232 card on the back of my computer. This is designated COM1
.
The other two ports (COM3
and COM4
) were created by USB-to-Null Modem cables. These entries still exist in the registry even though the cables have long since been detached (a COM8 existed for some time, but was removed after routinely plugging and unplugging USB cables a few times).
This is okay for me. I can always open up Putty or TeraTerm and check the available COM ports until I find the correct one. This isn't okay for the technicians that will be using this program. I don't know that the COM port will always be the same as they routinely shift USB cables about.
Is there any way (preferably programatically in C#) I can remove these stale entries or, at least, verify which ones are active?
Notes:
From the SerialPort.GetPortNames() MSDN documentation:
Remarks
The order of port names returned from GetPortNames is not specified.
Use the GetPortNames method to query the current computer for a list of valid serial port names. For example, you can use this method to determine whether COM1 and COM2 are valid serial ports for the current computer.
The port names are obtained from the system registry (for example, HKEY_LOCAL_MACHINE\HARDWARE\DEVICEMAP\SERIALCOMM). If the registry contains stale or otherwise incorrect data then the GetPortNames method will return incorrect data.
The following question: Removing COM Ports in Windows programmatically (Setup API ? ) is two years old and unsatisfactory. The only answer (essentialy "Have a look at Program X's source code and try to make something like that") is useless to me.