C#中使用serialport类枚举串口,并验证串口是否被占用
使用System.IO.Ports.SerialPort.GetPortNames()枚举可用串口并验证是否被占用,空闲串口添加到comobox1控件中显示。代码如下:
验证可用串口
1 public bool IsPortOpen()
2 {
3 //create vars for testing
4 bool _available = false;
5 SerialPort _tempPort;
6 String[] Portname = SerialPort.GetPortNames();
7
8 //create a loop for each string in SerialPort.GetPortNames
9 foreach (string str in Portname)
10 {
11 try
12 {
13 _tempPort = new SerialPort(str);
14 _tempPort.Open();
15
16 //if the port exist and we can open it
17 if (_tempPort.IsOpen)
18 {
19 comboBox1.Items.Add(str);
20 _tempPort.Close();
21 _available = true;
22 }23 }
24
25 //else we have no ports or can't open them display the
26 //precise error of why we either don't have ports or can't open them
27 catch (Exception ex)
28 {
29 MessageBox.Show(ex.ToString(), "Error - No Ports available", MessageBoxButtons.OK, MessageBoxIcon.Error);
30 _available = false;
31 }
32 }
33
34 //return the temp bool
35 return _available;
36 }