如何在Visual C#中打开连接之前检查COM端口是否存在

Fel*_*IOx 5 c# port serial-port exists visual-studio

我需要在连接之前检查选定的COM端口是否存在(它给出了错误)我正在使用Visual Studio Express 2013 C#.或者,有没有办法隐藏该错误?

谢谢..~理查德

Pet*_*ano 10

你应该做两件事.首先是检查System.IO.Ports.SerialPort.GetPortNames().这将告诉您端口是否存在.就像是:

var portExists = SerialPort.GetPortNames().Any(x => x == "COM1");
Run Code Online (Sandbox Code Playgroud)

如果已经在使用端口,则还需要在打开端口时捕获异常.

var port = new SerialPort("COM1");
try
{
    port.Open();
}
catch (Exception ex)
{
    // Handle exception
}
Run Code Online (Sandbox Code Playgroud)

现在,你需要小心和阅读http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.open(v=vs.110).aspx什么异常可以被抛出SerialPort.Open()来确保你适当地处理每个例外.


Eri*_*own 5

我使用System.IO.Ports.SerialPort.GetPortNames- 它返回一个可以打开的有效串行端口名称数组.


小智 1

使用 try/catch 并使用异常处理来告诉用户出了什么问题:

 SerPort = new SerialPort("COM8");

 try
 {
     SerPort.Open();
 }
 catch (Exception ex)
 {
     Console.WriteLine("Error opening port: {0}", ex.Message);
 } 
Run Code Online (Sandbox Code Playgroud)