Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 900
FelIOx Avatar asked Jan 31 '14 21:01

FelIOx


3 Answers

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.

like image 52
Pete Garafano Avatar answered Oct 18 '22 21:10

Pete Garafano


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

like image 22
Eric Brown Avatar answered Oct 18 '22 20:10

Eric Brown


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);
 } 
like image 1
sebastian s. Avatar answered Oct 18 '22 21:10

sebastian s.