在连接到选定的COM端口之前,我需要检查其是否存在(否则会出错)。我使用的是Visual Studio Express 2013 C#。是否有一些方法可以隐藏这个错误?
谢谢.. ~Richard
在连接到选定的COM端口之前,我需要检查其是否存在(否则会出错)。我使用的是Visual Studio Express 2013 C#。是否有一些方法可以隐藏这个错误?
谢谢.. ~Richard
你应该做两件事。第一件是检查 System.IO.Ports.SerialPort.GetPortNames()
。这将告诉你端口是否存在,类似于:
var portExists = SerialPort.GetPortNames().Any(x => x == "COM1");
如果端口已经被占用,您还需要在打开端口时捕获异常。
var port = new SerialPort("COM1");
try
{
port.Open();
}
catch (Exception ex)
{
// Handle exception
}
现在你需要小心并阅读 http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.open(v=vs.110).aspx ,了解 SerialPort.Open()
可能会抛出哪些异常,以确保你适当地处理每个异常。
我会使用System.IO.Ports.SerialPort.GetPortNames
方法 - 它返回一个包含可打开的有效串行端口名称的数组。
SerPort = new SerialPort("COM8");
try
{
SerPort.Open();
}
catch (Exception ex)
{
Console.WriteLine("Error opening port: {0}", ex.Message);
}