Kelly Anderson
Kelly Anderson

Reputation: 131

SerialPort.GetPortNames returns same port multiple times

SerialPort.GetPortNames();

is returning the following array:

{ "COM1", "COM5", "COM5", "COM5", "COM5", "COM5", "COM5" }

It normally only has each name once. Working around this is very easy, but does anyone know why it would ever do this?

Upvotes: 4

Views: 2602

Answers (1)

Peter Duniho
Peter Duniho

Reputation: 70652

Without a lot more information about your specific environment, including machine configuration and registry information, it's impossible to answer for sure. But most likely the (unsatisfying) answer is that GetPortNames() is just doing the best it can with the information available to it.

I.e. it examines the registry to see what ports exist and returns a list of them to you. In some cases, the same COM port number may be reused by multiple devices, or even multiple uses of the same device (depending on driver), causing the port number to be listed in the registry more than once.

Indeed, in some cases you may get a COM port name returned that isn't even valid at the moment. I.e. some device that did exist at some time, but which was removed/disconnected/etc. and is no longer usable.

It's a classic "garbage-in, garbage-out" issue.

For related information on the question, you might like to check out these Stack Overflow questions:

GetPortNames() returns stale data/Remove stale comport entries in Windows?
SerialPort.GetPortNames() is wrong
SerialPort.GetPortNames() behavior

Upvotes: 4

Related Questions