0

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.

Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
nabpp
  • 9
  • 4
  • 4
    It looks like you are re-using a single `comPort` instance over and over. I don't think you're supposed to be doing that. You should at least be calling `Close()` before you call `Open()` again, and you should probably be calling `Dispose()` and creating new instance with each iteration. – John Wu Aug 25 '22 at 17:57
  • To add to the previous comment: I see you are also using the `DataReceived` event. When you do this with a set of different objects, the `sender` argument to the method will be the specific instance that raised the event. – Joel Coehoorn Aug 25 '22 at 18:21
  • If you're device is a USB device, this [post](https://stackoverflow.com/a/65971845/10024425) may be useful. – Tu deschizi eu inchid Aug 25 '22 at 18:21

1 Answers1

0

I think John is right, you have to instanciate a new serial port for each port name. If you register an event, don't forget to unsubscribe. F.e. you can store the open comports in an collection to be able to close, deregister the event and dispose the serial port.