C # controlla se una porta COM (seriale) è già aperta
-
10-07-2019 - |
Domanda
Esiste un modo semplice per verificare a livello di programmazione se una porta COM seriale è già aperta / in uso?
Normalmente userei:
try
{
// open port
}
catch (Exception ex)
{
// handle the exception
}
Tuttavia, vorrei verificare a livello di programmazione in modo da poter tentare di utilizzare un'altra porta COM o alcune di queste.
Soluzione
Avevo bisogno di qualcosa di simile qualche tempo fa, per cercare un dispositivo.
Ho ottenuto un elenco di porte COM disponibili e poi ho semplicemente iterato su di esse, se non ha generato un'eccezione ho provato a comunicare con il dispositivo. Un po 'agitato ma funzionante.
var portNames = SerialPort.GetPortNames();
foreach(var port in portNames) {
//Try for every portName and break on the first working
}
Altri suggerimenti
Ecco come l'ho fatto:
[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);
poi più tardi
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();
}
La Classe SerialPort ha un Apri , che genererà alcune eccezioni. Il riferimento sopra contiene esempi dettagliati.
Vedi anche IsOpen proprietà.
Un semplice 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);
}
}
}
}
Questo è ciò che ha funzionato per me.
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;
}
Nel caso in cui è necessario catturare le eccezioni SerialPort (Open): https: //docs.microsoft.com/en-us/dotnet/api/system.io.ports.serialport.open?view=netframework-4.7.2
Puoi provare a seguire il codice per verificare se una porta è già aperta o meno. Presumo che tu non sappia specificamente quale porta vuoi controllare.
foreach (var portName in Serial.GetPortNames()
{
SerialPort port = new SerialPort(portName);
if (port.IsOpen){
/** do something **/
}
else {
/** do something **/
}
}