[英]System.IO.IOException error
I wrote a program that reads from the serial port. 我编写了一个从串行端口读取的程序。 No problem with the program run on the computer that has Visual Studio installed.
在安装了Visual Studio的计算机上运行的程序没有问题。 Everything is OK.
一切都好。 But when I copied release folder to another program and run it I have a error
System.IO.IOException
. 但是,当我将release文件夹复制到另一个程序并运行它时,出现错误
System.IO.IOException
。 I use this code to read data from serial port. 我使用此代码从串行端口读取数据。
byte[] buffer = new byte[42];
int readBytes = 0;
int totalReadBytes = 0;
int offset = 0;
int remaining = 41;
try
{
do
{
readBytes = serial.Read(buffer, offset, remaining);
offset += readBytes;
remaining -= readBytes;
totalReadBytes += readBytes;
}
while (remaining > 0 && readBytes > 0);
}
catch (TimeoutException ex)
{
Array.Resize(ref buffer, totalReadBytes);
}
UTF8Encoding enc = new UTF8Encoding();
recieved_data = enc.GetString(buffer, 27, 5);
Dispatcher.Invoke(DispatcherPriority.Send, new UpdateUiTextDelegate(WriteData), recieved_data);
How can I solve this problem ? 我怎么解决这个问题 ?
It seems that you are reading more bytes than the port have transmitted, you should check the BytesToRead
property to check how many they are. 似乎您正在读取的字节数比端口传输的字节数多,应该检查
BytesToRead
属性以检查它们的数量。
byte[] buffer = new byte[port.BytesToRead];
int readBytes = 0;
int totalReadBytes = 0;
int offset = 0;
int remaining = port.BytesToRead;
try
{
do
{
readBytes = serial.Read(buffer, offset, remaining);
offset += readBytes;
remaining -= readBytes;
totalReadBytes += readBytes;
}
while (remaining > 0 && readBytes > 0);
}
catch (TimeoutException ex)
{
Array.Resize(ref buffer, totalReadBytes);
}
May be helpful: 可能会有帮助:
http://zachsaw.blogspot.com/2010/07/net-serialport-woes.html http://zachsaw.blogspot.com/2010/07/net-serialport-woes.html
http://zachsaw.blogspot.com/2010/07/serialport-ioexception-workaround-in-c.html http://zachsaw.blogspot.com/2010/07/serialport-ioexception-workaround-in-c.html
But I haven't tested it. 但是我还没有测试过。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.