我正在开发一个从托盘运行的C#WinForms Windows应用程序.我需要为用户提供一些合理的错误处理和指令.为了测试我是否能够打开串行端口进行通信,我希望有一种方法来测试它是否已经打开或者由于某种原因它是不可打开的.
我想出了这个:
if (SerialPort.GetPortNames().Select((n) =>
n.ToUpperInvariant()).Contains(mycomportname))
{
// Port found, check to see if we can use it by test-opening
using (var sp = new SerialPort(mycomportname))
{
// Check to see if we can open this port
try
{
if (sp.IsOpen) throw new Exception("Serial port is already open");
sp.Open();
sp.Close();
}
catch (Exception ex)
{
throw new Exception("Serial port is in use");
}
}
}
else
{
// ...
}
commManager.PortName = mycomportname;
if (commManager.OpenPort())
{
// .. always …Run Code Online (Sandbox Code Playgroud)