System.IO.IO异常错误
本文关键字:IO 错误 异常 System | 更新日期: 2023-09-27 18:22:42
我写了一个从串行端口读取的程序。在安装了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);
我该如何解决这个问题?
如果您读取的字节数似乎超过了端口传输的字节数,则应检查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);
}
可能会有所帮助:
http://zachsaw.blogspot.com/2010/07/net-serialport-woes.html
http://zachsaw.blogspot.com/2010/07/serialport-ioexception-workaround-in-c.html
但我还没有测试过。