C# check if a COM (Serial) port is already open


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

Normally I would use:

    // 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.

3/20/2010 7:15:35 PM

Accepted Answer

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
10/12/2008 1:38:59 PM

This is how I did it:

      [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    internal static extern SafeFileHandle CreateFile(string lpFileName, int dwDesiredAccess, int dwShareMode, IntPtr securityAttrs, int dwCreationDisposition, int dwFlagsAndAttributes, IntPtr hTemplateFile);

then later on

        int dwFlagsAndAttributes = 0x40000000;

        var portName = "COM5";

        var isValid = SerialPort.GetPortNames().Any(x => string.Compare(x, portName, true) == 0);
        if (!isValid)
            throw new System.IO.IOException(string.Format("{0} port was not found", portName));

        //Borrowed from Microsoft's Serial Port Open Method :)
        SafeFileHandle hFile = CreateFile(@"\\.\" + portName, -1073741824, 0, IntPtr.Zero, 3, dwFlagsAndAttributes, IntPtr.Zero);
        if (hFile.IsInvalid)
            throw new System.IO.IOException(string.Format("{0} port is already open", portName));


        using (var serialPort = new SerialPort(portName, 115200, Parity.None, 8, StopBits.One))

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow