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

前端 未结 7 2018
南旧
南旧 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:45

    Sharing what worked for me (a simple helper method):

    private string portName { get; set; } = string.Empty;
    
        /// 
        /// Returns SerialPort Port State (Open / Closed)
        /// 
        /// 
        internal bool HasOpenPort()
        {
            bool portState = false;
    
            if (portName != string.Empty)
            {
                using (SerialPort serialPort = new SerialPort(portName))
                {
                    foreach (var itm in SerialPort.GetPortNames())
                    {
                        if (itm.Contains(serialPort.PortName))
                        {
                            if (serialPort.IsOpen) { portState = true; }
                            else { portState = false; }
                        }
                    }
                }
            }
    
            else { System.Windows.Forms.MessageBox.Show("Error: No Port Specified."); }
    
            return portState;
    }
    


    Notes:
    - For more advanced technique(s) I recommend using ManagementObjectSearcher Class.
    More info Here.
    - For Arduino devices I would leave the Port Open.
    - Recommend using a Try Catch block if you need to catch exceptions.
    - Check also: "TimeoutException"
    - More information on how to get SerialPort (Open) Exceptions Here.

提交回复
热议问题