简体   繁体   English

VS C#列表可用(未使用)串行端口

[英]VS C# List Available (Not in Use) Serial Ports

I am writing my first ever program in C# using Visual Studio, I have a function that populates a dropdown with 'available' COM ports. 我正在使用Visual Studio用C#编写我的第一个程序,我有一个用“可用” COM端口填充下拉列表的函数。 How do I check if one of these 'available' ports is not open outside of my program? 如何检查这些“可用”端口之一是否在程序外部未打开?

    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);
        }
    }

I hoped to do this but it does not work. 我希望这样做,但是没有用。

When you initialize serialPort1 ? 初始化serialPort1

You should create a new instance of SerialPort , and open it to know if it's free like this: 您应该创建一个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 有关“ SerialPort”类的更多信息

EDIT: 编辑:

The best solution is follow @Baddack comment: 最好的解决方案是遵循@Baddack注释:

"Hans Passant said it the best: "Such code can never work reliably on a multi-tasking operating system. “汉斯·帕桑特(Hans Passant)说得最好:“这种代码永远无法在多任务操作系统上可靠地工作。 You cannot find out until you call Open(). 您必须先调用Open()才能找到答案。 At which point you get a crystal-clear exception.". You should really just populate the combobox with all the COM ports and let the user decide. If the COM port is in use, then a exception is thrown and you can handle that however you please." 此时,您将获得明确的异常。”。您实际上应该只用所有COM端口填充组合框,然后由用户决定。如果使用了COM端口,则将引发异常,但是您可以处理该异常。你先请。”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM