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

前端 未结 7 2016
南旧
南旧 2020-12-05 03:27

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
}
cat         


        
7条回答
  •  臣服心动
    2020-12-05 03:52

    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);
            }
        }
      }
    }
    

提交回复
热议问题