views:

6791

answers:

3

Is there an easy way of programmatically checking if a serial COM port is already open/being used?

Normally I would use:

try
{
    // open port
}
catch (Exception ex)
{
    // handle the exception
}

However, I would like to programatically check so I can attempt to use another COM port or some such.

+2  A: 

I needed something similar some time ago, to search for a device.

I obtained a list of available COM ports and then simply iterated over them, if it didn't throw an exception i tried to communicate with the device. A bit rough but working.

var portNames = SerialPort.GetPortNames();

foreach(var port in portNames) {
    //Try for every portName and break on the first working
}
Fionn
I was really hoping for a more 'elegant' solution... but when all else fails 'use any means possible to make the program work'!
TK
+1  A: 

The SerialPort class has an Open method, which will throw a few exceptions. The reference above contains detailed examples.

See also, the IsOpen property.

A simple test:

using System;
using System.IO.Ports;
using System.Collections.Generic;
using System.Text;

namespace SerPort1
{
class Program
{
    static private SerialPort MyPort;
    static void Main(string[] args)
    {
        MyPort = new SerialPort("COM1");
        OpenMyPort();
        Console.WriteLine("BaudRate {0}", MyPort.BaudRate);
        OpenMyPort();
        MyPort.Close();
        Console.ReadLine();
    }

    private static void OpenMyPort()
    {
        try
        {
            MyPort.Open();
        }
        catch (Exception ex)
        {
            Console.WriteLine("Error opening my port: {0}", ex.Message);
        }
    }
  }
}
gimel
IsOpen will only be truw if the Open() method was ever called. It won't say if the port has been opened by another app.
Mark Cidade
A: 

You can try folloing code to check whether a port already open or not. I'm assumming you dont know specificaly which port you want to check.

foreach (var portName in Serial.GetPortNames()
{
  SerialPort port = new SerialPort(portName);
  if (port.IsOpen){
    /** do something **/
  }
  else {
    /** do something **/
  }
}
Funky81