Reputation: 197
I wrote a program that reads from the serial port. No problem with the program run on the computer that has Visual Studio installed. Everything is OK. But when I copied release folder to another program and run it I have a error 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 ?
Upvotes: 1
Views: 1476
Reputation: 7629
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.
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);
}
Upvotes: 1
Reputation: 5373
May be helpful:
http://zachsaw.blogspot.com/2010/07/net-serialport-woes.html
http://zachsaw.blogspot.com/2010/07/serialport-ioexception-workaround-in-c.html
But I haven't tested it.
Upvotes: 0