• c# 串口调试


    public bool IsCommPortValid(int port)
    
    {
        try
        {
        SerialPort sp = new SerialPort("COM"+port.ToString());
        sp.Close();
        }
        catch
        {
            return false;
        }
    }

    用个try,catch抓一下,串口占用直接会报占用的错误,打印出来就行了啊

                    string port = null;
                    port = Console.ReadLine();
                    SerialPort sp = new SerialPort("COM" + port);
                    try
                    {
                        sp.Open();
                        Thread.Sleep(1000);
                        sp.Close();
                            Console.WriteLine("端口尚未打开");
                    }
                    catch (InvalidOperationException e)
                    {
                        Console.WriteLine("端口已打开");
                    }
                    catch(Exception ee)
                    {
                        Console.WriteLine( new Exception(ee.Message));
                    }

    测试

    string port = null;
    port = Console.ReadLine();
    SerialPort sp1 = new SerialPort("COM1");
    sp1.Open();
    SerialPort sp = new SerialPort("COM" + port);
    try
    {
        sp.Open();
        sp.Close();
        Console.WriteLine("端口尚未打开");
    }
    catch (InvalidOperationException e)
    {
        Console.WriteLine("端口已打开");
    }
    catch(Exception ee)
    {
        Console.WriteLine( new Exception(ee.Message));
    }
    发现自己的不足,善于利用找到的方法去扬长避短。行动起来。
  • 相关阅读:
    Java ArrayList,LinkedList使用
    Vue 使用axios分片上传
    Vue 中Axios 使用
    Vue 自定义组件
    Java IO系统--RandomAccessFile
    Java IO系统--字符流
    Java String类
    静态导入(static import)
    枚举(Enum)
    Java 可变参数
  • 原文地址:https://www.cnblogs.com/rechen/p/5077698.html
Copyright © 2020-2023  润新知