C# – SerialPort.GetPortNames() behavior

cserial-portvisual-studio-2008

In my C# 2008 application, I use the SerialPort.GetPortNames() function to retrieve the list of currently available ports. What I have noticed is, when ever I plug in a USB device, it's port number i s shown in the list on my Application and when I unplug it and refresh the list, the port number is no longer there.

One phase of the application involves reading/writing data from/to the device continuously. Now, my expectation is, If I unplug the device during the operation and get the current Port list using SerialPort.GetPortNames(), the Port Name will not be there and I can use that to make the decision that the device has been unplugged.

To my surprise, the Port name is still found despite having it removed

Why is the program behaving like this? The port name isn't listed when in no-communication mode. Does it have something to do with the device being removed when it's communicating?

Best Answer

You have to be talking about SerialPort.GetPortNames(), "GetPortList" doesn't make sense. The function iterates values in the registry, written there by your USB emulator device driver. You can have a look-see with Regedit.exe, navigate to HKLM\Hardware\DeviceMap\SerialComm. Unplug it, press F5, if the COM port is still there then SerialPort doesn't know any better than the port still being present.

There is no prescribed behavior as to how a serial port device driver should behave when the port suddenly vanishes. Serial ports are very primitive, they date back to an era where "bug" meant a moth gumming up the teletype. There is no hardware support at all for Plug and Play, removing a port with the power turned on is equivalent to unplugging the disk drive while Windows is swapping to the paging file.

Most device drivers return an error code, it generates an uncatchable exception that crashes your program. The subject of this feedback article. Apparently your device driver doesn't do that, which ought to be preferable over bombing your program. Encouraging btw, most USB emulator device drivers are utter junk.

The ultimate workaround is simple: put a little tag on the plug "don't disconnect while in use!" It's kinda of a problem with USB, most people look at it and go "hmm, what can I do with it?". And arrive at the only answer and unplug it. After a couple of kabooms, they'll learn to not do that anymore.

Related Topic