How to check if COM port exist before opening connection in Visual C#

28,794

Solution 1

You should be doing two things. The first is checking System.IO.Ports.SerialPort.GetPortNames(). This will tell you if the port exists. Something like:

var portExists = SerialPort.GetPortNames().Any(x => x == "COM1");

You also need to catch exceptions when opening the port if it is already in use.

var port = new SerialPort("COM1");
try
{
    port.Open();
}
catch (Exception ex)
{
    // Handle exception
}

Now you need to be careful and read http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.open(v=vs.110).aspx for what exceptions can be thrown by SerialPort.Open() to make sure you handle each exception appropriately.

Solution 2

I'd use System.IO.Ports.SerialPort.GetPortNames - it returns an array of valid serial port names that can be opened.

Solution 3

Use try/catch and use exception handling to tell your user whats wrong:

 SerPort = new SerialPort("COM8");

 try
 {
     SerPort.Open();
 }
 catch (Exception ex)
 {
     Console.WriteLine("Error opening port: {0}", ex.Message);
 } 
Share:
28,794
FelIOx
Author by

FelIOx

Updated on July 05, 2022

Comments

  • FelIOx
    FelIOx almost 2 years

    I need to check if selected COM port exist before conecting to it (It gives error) I'm using Visual Studio Express 2013 C#. Or, is there some way to hide that error?

    Thanks.. ~Richard

  • sebastian s.
    sebastian s. over 10 years
    nice one... but i would also check if the available ones already open with SerialPort.IsOpen property...
  • Scott Chamberlain
    Scott Chamberlain over 10 years
    @sebastians. Checking to see if it is available then trying to open is pointless because you have a small windows someone else could open the port between your check and opening it. Since you would need the error checking code anyway just let the error handler handle it. Handling situations where resources are in use by other processes is one of the few situations where flow of control exception handling is ok.