C#检查COM(串行)端口是否打开通常我会使用:try{//openport}catch(Exceptionex){//handletheexception}但是,我想以编程方式进行检查,以便我可以尝试另一个COM端口或类似的东西。我刚才需要类似的东西来搜索设备。我得到可用COM端口的列表,然后简单地遍历它们,如果它没有抛出异常,我会尝试与设备通信。有点粗糙但有效。varportNames=SerialPort.GetPortNames();foreach(varportinportNames){//尝试每个端口名称并在第一个工作时中断}这就是我做的方式:[DllImport("kernel32.dll",CharSet=CharSet.Auto,SetLastError=true)]internalstaticexternSafeFileHandleCreateFile(stringlpFileName,intdwDesiredAccess,intdwShareMode,IntPtrsecurityAttrs,intdwCreationDisposition,intdwFlagsAndAttributes,IntPtrhTemplateFile);然后是intdwFlagsAndAttributes=0x40000000;var端口名="COM5";varisValid=SerialPort.GetPortNames().Any(x=>string.Compare(x,portName,true)==0);if(!isValid)thrownewSystem.IO.IOException(string.Format("{0}portwasnotfound",portName));//借用微软的串口打开方法:)SafeFileHandlehFile=CreateFile(@"\."+portName,-1073741824,0,IntPtr.Zero,3,dwFlagsAndAttributes,IntPtr.Zero);if(hFile.IsInvalid)thrownewSystem.IO.IOException(string.Format("{0}端口已经打开",portName));hFile.Close();使用(varserialPort=newSerialPort(portName,115200,Parity.None,8,StopBits.One)){serialPort.Open();SerialPort类有一个Open方法,它会抛出一些异常上面的参考包含详细的例子。另请参见IsOpen属性。一个简单的测试:使用系统;使用System.IO.Ports;使用System.Collections.Generic;使用系统文本;命名空间SerPort1{类程序{staticprivateSerialPortMyPort;staticvoidMain(string[]args){MyPort=newSerialPort("COM1");打开我的端口();Console.WriteLine("波特率{0}",MyPort.BaudRate);打开我的端口();我的端口.关闭();控制台.ReadLine();}privatestaticvoidOpenMyPort(){try{MyPort.Open();}catch(Exceptionex){Console.WriteLine("打开我的端口时出错:{0}",ex.Message);}}}}这对我有用。私有字符串端口名{得到;放;}=string.Empty;//////返回SerialPort端口状态(打开/关闭)//////internalboolHasOpenPort(){boolportState=false;如果(portName!=string.Empty){使用(SerialPortserialPort=newSerialPort(portName)){foreach(SerialPort.GetPortNames()中的varitm){如果(itm.Contains(serialPort.PortName)){如果(serialPort。IsOpen){portState=true;}else{portState=false;}}}}}else{System.Windows.Forms.MessageBox.Show("错误:未指定端口。");}返回端口状态;如果您需要捕获SerialPort(open)异常:https://docs.microsoft.com/en-us/dotnet/api/system.io.ports.serialport.open?view=networkframe-4.7.2你可以尝试下面的代码来检查端口是否打开。我假设您不确切知道要检查哪个端口。以上是C#学习教程:C#检查COM(串口)端口是否打开。如果对大家有用,需要详细了解C#学习教程,希望大家多加关注—foreach(varportNameinSerial.GetPortNames(){SerialPortport=newSerialPort(portName);if(port.IsOpen){/**dosomething**/}else{/**dosomething**/}}本文收集自网络,不代表立场,如有侵权,请点击右边联系管理员删除,如需转载请注明出处:
