码迷,mamicode.com
首页 > Windows程序 > 详细

c# 串口调试

时间:2015-12-26 11:33:12      阅读:196      评论:0      收藏:0      [点我收藏+]

标签:

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

 

c# 串口调试

标签:

原文地址:http://www.cnblogs.com/rechen/p/5077698.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!