Thursday, 8 September 2011

Retrieving available COM ports

I recently had to deal with a dodgy USB driver that didn't null-terminal it's virtual com-ports in the registry. As a result, when retrieving the ports-list via the usual SerialPort.GetPortNames(), I got values like "COM7รข".

Here's a little method to not only remove any unwanted characters from the port-names, but (using an anonymous delegate to implement an IComparer on the Sort() extension method) order the list of COM ports by port-number too (otherwise COM11 would come before COM2):