I am writing an application that will loop through my computer's com ports. The issue I am having is one of the com ports is opened on PC startup by another process which causes an exception to be thrown:
System.InvalidOperationException: 'The port is already open.'
I have successfully handled the exception but it seems to break the foreach
loop once it hits the exception and will not continue to the other ports. Am I handling the expectation correctly by having the try catch block inside of the foreach loop?
private void Rescan()
{
bool error = false;
int baud = 115200;
string[] ports = SerialPort.GetPortNames();
foreach (string port in ports)
{
try
{
comPort.PortName = port;
comPort.BaudRate = baud; //convert Text to Integer
comPort.Open();
comPort.DtrEnable = true;
comPort.DataReceived += SerialPortDataReceived;
System.Windows.MessageBox.Show(port.ToString());
}
catch (InvalidOperationException e)
{
System.Windows.MessageBox.Show("");
}
}
}
I know it can be dangerous and poor programing practice to open ALL com ports that are not mine, so my end goal is to open each com port and write some string like "ID_DEVICE" which will then prompt a response from the firmware of the device I am trying to connect to (Arduino). If the com port does not have a proper response then my application will close that specific port and only leave open the ports that had the proper response.