PortName property of the SerialPort class will list all serial port that is connectted the pc.
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | string[] ports = SerialPort.GetPortNames(); foreach (string portName in ports) { try { Console.WriteLine(portName);//read available port names var port = new SerialPort(portName, 256000); port.Open(); } catch (Exception ex) { Console.WriteLine(ex.Message); } } |
if you want to connect directly any port , you can chance portName variable and get connection.
In following example:
I entered com3 and connected it
1 2 3 4 5 6 7 8 9 10 11 12 13 | SerialPort mySerialPort = new SerialPort( "COM3", 9600); try { mySerialPort.Open(); mySerialPort.Close(); Console.WriteLine(mySerialPort.PortName); } catch (IOException ex) { Console.WriteLine(ex); } |
string[] ports = SerialPort.GetPortNames();
foreach (string portName in ports)
{
try
{
Console.WriteLine(portName);//read available port names
var port = new SerialPort(portName, 256000);
port.Open();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}