VS C# 列表可用(未使用)串口
VS C# List Available (Not in Use) Serial Ports
我正在使用 Visual Studio 在 C# 中编写我的第一个程序,我有一个函数可以使用 'available' 个 COM 端口填充下拉列表。如何检查这些 'available' 端口之一是否未在我的程序之外打开?
foreach (string portName in System.IO.Ports.SerialPort.GetPortNames())
{
serialPort1.PortName = portName;
if (serialPort1.IsOpen == false) // Only list if it is not in use - does not work - .IsOpen is only valid from within this app
{
CommsBox.Items.Add(portName);
}
}
我希望这样做,但没有成功。
什么时候初始化serialPort1
?
您应该创建一个 SerialPort
的新实例,然后像这样打开它以了解它是否免费:
foreach (string portName in System.IO.Ports.SerialPort.GetPortNames())
{
try{
SerialPort serialPort1 = new SerialPort();
serialPort1.PortName = portName;
serialPort1.Open();
CommsBox.Items.Add(portName); //If you can open it it's because it was free, so we can add it to available
serialPort1.Close(); //Should close it again
}
catch (Exception ex){
//manage the exception...
}
}
More information about 'SerialPort' class
编辑:
最好的解决方案是关注@Baddack 评论:
"Hans Passant said it the best: "这样的代码永远无法在多任务操作系统上可靠地工作。在调用 Open() 之前,您无法找到答案。此时你会得到一个 crystal-clear exception。可以随心所欲地处理。"
我正在使用 Visual Studio 在 C# 中编写我的第一个程序,我有一个函数可以使用 'available' 个 COM 端口填充下拉列表。如何检查这些 'available' 端口之一是否未在我的程序之外打开?
foreach (string portName in System.IO.Ports.SerialPort.GetPortNames())
{
serialPort1.PortName = portName;
if (serialPort1.IsOpen == false) // Only list if it is not in use - does not work - .IsOpen is only valid from within this app
{
CommsBox.Items.Add(portName);
}
}
我希望这样做,但没有成功。
什么时候初始化serialPort1
?
您应该创建一个 SerialPort
的新实例,然后像这样打开它以了解它是否免费:
foreach (string portName in System.IO.Ports.SerialPort.GetPortNames())
{
try{
SerialPort serialPort1 = new SerialPort();
serialPort1.PortName = portName;
serialPort1.Open();
CommsBox.Items.Add(portName); //If you can open it it's because it was free, so we can add it to available
serialPort1.Close(); //Should close it again
}
catch (Exception ex){
//manage the exception...
}
}
More information about 'SerialPort' class
编辑:
最好的解决方案是关注@Baddack 评论:
"Hans Passant said it the best: "这样的代码永远无法在多任务操作系统上可靠地工作。在调用 Open() 之前,您无法找到答案。此时你会得到一个 crystal-clear exception。可以随心所欲地处理。"