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

c# 串口调试

2015-12-26 10:50 561 查看
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));
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: