System.IO.IOException错误

时间:2013-07-17 11:56:16

标签: c# exception io

我写了一个从串口读取的程序。在安装了Visual Studio的计算机上运行程序没问题。一切都好。但是当我将release文件夹复制到另一个程序并运行它时,我有一个错误System.IO.IOException。我使用此代码从串口读取数据。

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

我该如何解决这个问题?

2 个答案:

答案 0 :(得分:1)

您似乎正在读取比端口传输的更多字节,您应该检查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);
}

答案 1 :(得分:0)