简体   繁体   中英

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. 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 ?

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM