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

前端 未结 7 1988
南旧
南旧 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:30

    For people that cannot use SerialPort.GetPortNames(); because they are not targeting .net framework (like in my case I am using .Net Core and NOT .Net Framework) here is what I ended up doing:

    In command prompt if you type mode you get something like this:

    mode is an executable located at C:\Windows\System32\mode.com. Just parse the results of that executable with a regex like this:

    // Code that answers the question
    
    var proc = new Process
    {
        StartInfo = new ProcessStartInfo
        {
            FileName = @"C:\Windows\System32\mode.com",
            UseShellExecute = false,
            RedirectStandardOutput = true,
            CreateNoWindow = true
        }
    };
    
    proc.Start();
    proc.WaitForExit(4000); // wait up to 4 seconds. It usually takes less than a second
    
    // get ports being used
    var output = proc.StandardOutput.ReadToEnd();
    

    Now if you want to parse the output this is how I do it:

    List<string> comPortsBeingUsed = new List<string>();
    Regex.Replace(output, @"(?xi) status [\s\w]+? (COM\d) \b ", regexCapture =>
    {
        comPortsBeingUsed.Add(regexCapture.Groups[1].Value);
        return null;
    });
    
    foreach(var item in comPortsBeingUsed)
    {
        Console.WriteLine($"COM port {item} is in use");
    }
    
    0 讨论(0)
  • 2020-12-05 03:31

    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 **/
      }
    }
    
    0 讨论(0)
  • 2020-12-05 03:33

    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));
    
            hFile.Close();
    
    
            using (var serialPort = new SerialPort(portName, 115200, Parity.None, 8, StopBits.One))
            {
                serialPort.Open();
            }
    
    0 讨论(0)
  • 2020-12-05 03:45

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

    private string portName { get; set; } = string.Empty;
    
        /// <summary>
        /// Returns SerialPort Port State (Open / Closed)
        /// </summary>
        /// <returns></returns>
        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.

    0 讨论(0)
  • 2020-12-05 03:50
      public void MobileMessages(string ComNo, string MobileMessage, string MobileNo)
        {
            if (SerialPort.IsOpen )
                SerialPort.Close();
            try
            {
                SerialPort.PortName = ComNo;
                SerialPort.BaudRate = 9600;
                SerialPort.Parity = Parity.None;
                SerialPort.StopBits = StopBits.One;
                SerialPort.DataBits = 8;
                SerialPort.Handshake = Handshake.RequestToSend;
                SerialPort.DtrEnable = true;
                SerialPort.RtsEnable = true;
                SerialPort.NewLine = Constants.vbCrLf;
                string message;
                message = MobileMessage;
    
                SerialPort.Open();
                if (SerialPort.IsOpen  )
                {
                    SerialPort.Write("AT" + Constants.vbCrLf);
                    SerialPort.Write("AT+CMGF=1" + Constants.vbCrLf);
                    SerialPort.Write("AT+CMGS=" + Strings.Chr(34) + MobileNo + Strings.Chr(34) + Constants.vbCrLf);
                    SerialPort.Write(message + Strings.Chr(26));
                }
                else
                    ("Port not available");
                SerialPort.Close();
                System.Threading.Thread.Sleep(5000);
            }
            catch (Exception ex)
            {
    
                    message.show("The port " + ComNo + " does not exist, change port no ");
            }
        }
    
    0 讨论(0)
  • 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);
            }
        }
      }
    }
    
    0 讨论(0)
提交回复
热议问题