用try吧
if(!com.IsOpen)
{
//设置属性 try
{
com.Open();
} catch(Exception)
{
com.Close();
com.Dispose();
}
}
if(!com.IsOpen)
{
//设置属性 try
{
com.Open();
} catch(Exception)
{
com.Close();
com.Dispose();
}
}
解决方案 »
- 请问sender发生改变,怎么写
- 菜鸟提问,关于按钮可用问题,谢谢
- 在DataGridView中添加自动汇总行
- 一条sql语句,请赐教
- C1FlexGrid关于行拷贝的问题,谢谢。
- listview的多行选中的问题
- 简单的多文档颜色控制问题!!帮忙了啊,等待中!!
- VB6可以开发出给C#的COM组件,C#可以开发出可供VB6或非.net 框架的程序使用吗?如VB6,delphi 等?
- 如何把多个已经编译好的dll(c#产生的)合并成为一个?
- 请问 int i=Console.Read() -'0'; 中,后面加 -'0'是什么意思
- 初学者请教一个接口函数调用的问题
- 求助,c#文件中写入中文时自动产生bom
代码:using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;
using System.IO;namespace SerialPortTest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
SerialPort gpsPort = new SerialPort("COM4", 9600, Parity.None, 8, StopBits.One);
private void button1_Click(object sender, EventArgs e)
{
//gpsPort.PortName = "COM4";
//bool flag = gpsPort.IsOpen;
//gpsPort.Open();
//string[] str = new string[100];
//str = SerialPort.GetPortNames(); try
{
gpsPort.Open();
}
catch (System.Exception ex)
{
FileStream fileStream = new FileStream("\\log.txt", FileMode.Create);
StreamWriter sw = new StreamWriter(fileStream, Encoding.Default);
sw.Write(ex.ToString());
sw.Close();
}
//int i;
//byte[] buf = { 1, 2, 3 };
//gpsPort.Write(buf, 0, buf.Length);
gpsPort.Close();
}
}
}
log:
System.IO.IOException: IOException
位于 System.IO.Ports.SerialStream.WinIOError(Int32 errorCode, String str)
位于 System.IO.Ports.SerialStream.WinIOError(Int32 err)
位于 System.IO.Ports.SerialStream.CheckResult(Int32 err)
位于 System.IO.Ports.SerialStream.InitializeDCB(Int32 baudRate, Parity parity, Int32 dataBits, StopBits stopBits, Boolean discardNull)
位于 System.IO.Ports.SerialStream..ctor(String portName, Int32 baudRate, Parity parity, Int32 dataBits, StopBits stopBits, Int32 readTimeout, Int32 writeTimeout, Handshake handshake, Boolean dtrEnable, Boolean rtsEnable, Boolean discardNull, Byte parityReplace)
位于 System.IO.Ports.SerialPort.Open()
位于 SerialPortTest.Form1.button1_Click(Object sender, EventArgs e)
位于 System.Windows.Forms.Control.OnClick(EventArgs e)
位于 System.Windows.Forms.Button.OnClick(EventArgs e)
位于 System.Windows.Forms.ButtonBase.WnProc(WM wm, Int32 wParam, Int32 lParam)
位于 System.Windows.Forms.Control._InternalWnProc(WM wm, Int32 wParam, Int32 lParam)
位于 Microsoft.AGL.Forms.EVL.EnterMainLoop(IntPtr hwnMain)
位于 System.Windows.Forms.Application.Run(Form fm)
位于 SerialPortTest.Program.Main()
那看下有没别的程序使用了COM4,比如串口助手之类的
好奇怪,我用你的代码试了下没问题的。
你的错误日志没怎么看懂,取消catch,看看会报什么错还有种可能就是,你在自己的程序里别的地方打开了COM4但是没关闭
此端口处于无效状态。 - 或 - 尝试设置基础端口状态失败。例如,从此 SerialPort 对象传递的参数无效。
既然C++能用,那端口无效状态基本可以排除。而且可以确定端口不是被占用了(因为被占用报的是InvalidOperationException)。所以应该是设置基础端口状态失败。设断点看看里面的属性值都对不对。跟C++的对比一下。
SerialPort gpsPort = new SerialPort("COM4", 9600, Parity.None, 8, StopBits.One);
这一段C++怎么写的
要不就是其它程序占用的,要不就是这个程序本身占用的。
很可能是你用C++调用的时候就占用了,没释放。重启一下机器,然后什么都别运行,就直接跑你的程序试试。
这是我的代码 希望能对你有所帮助SerialPort com;
string port = "COM5";
public void SerialPort_Open(string str)
{
try
{
com = new SerialPort();
//USB端口串行波特率
com.BaudRate = 9600;
//设置通信端口,包括但不限于所有可用的COM端口
com.PortName = port;
//获取说设置每个字节的标准数据位长度
com.DataBits = 8;
if (com != null)
{
if (com.IsOpen)
{
com.Close();
}
}
//打开串口
com.Open();
Byte[] TxData = Write(str);
com.Write(TxData, 0, TxData.Length);
com.DataReceived += new SerialDataReceivedEventHandler(com_DataReceived);
com.Close();
}
catch (Exception ex)
{
WriteLog("外部端口连接错误!" + ex.Message, ConfigurationManager.AppSettings["Error"]);
timer2.Enabled = false;
timer1.Enabled = false;
button18.Visible = false;
button2.Visible = true;
this.Text = "打印监控----已停止";
Statue = false;
if (connection.State == System.Data.ConnectionState.Broken || connection.State == System.Data.ConnectionState.Open)
{
connection.Close();
}
} }
另外一帖子,200分求助
我这个例子是在ce5下调用串口打印机的。
http://download.csdn.net/detail/mjp1234airen4385/1664218
初步怀疑是这个cab包里的什么类库或功能引起访问串口的类库失效了。
自己做一个空的cab包也会失败,空的cab包,里面就放一个txt之类的,这有影响吗
看看这些类库有没有对硬件资源访问的类库造成影响。
Version: 3.5.0.0
Name: System, Version=3.5.0.0, Culture=neutral, PublicKeyToken=969db8053d3322ac, Retargetable=Yes 但是反编译工具不太会用,我的程序要部署到掌机上,用的dll应该是掌机上的吧,不是pc上的吧
Signature="$Windows NT$"
Provider="Thinta"
CESignature="$Windows CE$"[CEStrings]
AppName="CESetupCab"
InstallDir=%CE1%\%AppName%[Strings]
Manufacturer="Thinta"[CEDevice]
VersionMin=4.0
VersionMax=6.99
BuildMax=0xE0000000[DefaultInstall]
CEShortcuts=Shortcuts
AddReg=RegKeys
CopyFiles=Files.Common1,Files.Common2,Files.Common3,Files.Common4,Files.Common5
CESetupDLL="CESetup.dll"[SourceDisksNames]
1=,"Common1",,"C:\Users\friendy\Desktop\CESetup\CESetupCab\"
2=,"Common2",,"C:\Users\friendy\Desktop\CESetup\CESetupCab\"
3=,"Common3",,"C:\Users\friendy\Desktop\CESetup\CESetupCab\"
4=,"Common4",,"C:\Users\friendy\Desktop\CESetup\CESetupCab\"
5=,"Common5",,"C:\Users\friendy\Desktop\CESetup\CESetup\T31-SDK01 (ARMV4I)\Release\"[SourceDisksFiles]
"T30Service.dll"=1
"T30ServiceApiDll.dll"=2
"T6DeviceDll.dll"=3
"T6FactoryTest.exe"=4
"CESetup.dll"=5[DestinationDirs]
Shortcuts=0,%CE2%\Start Menu
Files.Common1=0,"%CE2%"
Files.Common2=0,"%CE2%"
Files.Common3=0,"%CE2%"
Files.Common4=0,"%InstallDir%"
Files.Common5=0,"%InstallDir%"[Files.Common1]
"T30Service.dll","T30Service.dll",,0[Files.Common2]
"T30ServiceApiDll.dll","T30ServiceApiDll.dll",,0[Files.Common3]
"T6DeviceDll.dll","T6DeviceDll.dll",,0[Files.Common4]
"T6FactoryTest.exe","T6FactoryTest.exe",,0[Files.Common5]
"CESetup.dll","CESetup.dll",,0
[Shortcuts][RegKeys]
"HKLM","ZZRD","CABVer","0x00000000","1.0.0.4"
"T6DeviceDll.dll","T6DeviceDll.dll",,0
吧这个类库打开,看看里面有什么访问串口类的函数,也许是它造成的。
你串口打开的参数类型过少,有些必须需要设置的,你没有设置。