1

我写了一个从串口读取的程序。在安装了 Visual Studio 的计算机上运行的程序没有问题。一切都好。但是当我将发布文件夹复制到另一个程序并运行它时,我有一个错误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);

我怎么解决这个问题 ?

4

2 回答 2

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);
}
于 2013-07-17T12:40:57.513 回答
0

可能会有所帮助:

http://zachsaw.blogspot.com/2010/07/net-serialport-woes.html

http://zachsaw.blogspot.com/2010/07/serialport-ioexception-workaround-in-c.html

但我没有测试过。

于 2013-07-17T12:23:13.293 回答