Hi, it is rather simple to try a series of port names, as in the following code:
// get a list of existing serial ports
public static object[] GetSerialPorts() {
ArrayList ports=new ArrayList();
byte[] bytes=new byte[1024];
for (int port=1; port<30; port++) {
string portName="COM"+port;
int size=1024;
// getting default settings succeeds if device exists,
// independent of port wnership
bool exists=GetDefaultCommConfig(portName, bytes, ref size);
if (exists) ports.Add(portName);
}
return ports.ToArray();
}
// get Windows port parameters (fails for non-existing ports)
[DllImport("kernel32.dll", CharSet=CharSet.Ansi,
CallingConvention=CallingConvention.Cdecl)]
public static extern bool GetDefaultCommConfig(string portName, byte[] buf,ref int bufSize);
The above works on all .NET versions. Starting with .NET 2.0 you can use SerialPort.GetPortNames() to get all serial port names (also those that are not COM#). :)
Luc Pattyn [My Articles]