您的位置:首页 > 编程语言 > C#

c#验证串口可用性

2015-09-11 00:19 435 查看
public bool IsPortOpen()
{
//create vars for testing
bool _available = false;
SerialPort _tempPort;
String[] Portname = SerialPort.GetPortNames();

//create a loop for each string in SerialPort.GetPortNames
foreach (string str in Portname)
{
try
{
_tempPort = new SerialPort(str);
_tempPort.Open();

//if the port exist and we can open it
if (_tempPort.IsOpen)
{
comboBox1.Items.Add(str);
_tempPort.Close();
_available = true;
}
}

//else we have no ports or can't open them display the
//precise error of why we either don't have ports or can't open them
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), "Error - No Ports available", MessageBoxButtons.OK, MessageBoxIcon.Error);
_available = false;
}
}

//return the temp bool
return _available;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: