【问题标题】:System.IO.IOException errorSystem.IO.IOException 错误
【发布时间】:2013-07-15 23:16:10
【问题描述】:

我写了一个从串口读取的程序。在安装了 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);

我该如何解决这个问题?

【问题讨论】:

  • 请添加有关异常的更多详细信息。了解 exat 信息会对我们有很大帮助。另外,all 是您的代码吗?您是否也在使用一些非 .NET 库?
  • 2 个人需要撤销他们的投票权......这个问题,就目前而言,不可能对其他人有用......
  • 是的,我确定trippino
  • 端口很可能不一样。我的意思是,第一台机器上的 COM1 和另一台机器上的 COM2。无论如何:请查看您的帖子标题和正文.. 可能您的意思不是“另一个程序”,您的意思是“另一个机器”,还有更多关于异常的详细信息,ToString() 方法的转储例如异常对象。

标签: c# exception io


【解决方案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);
}

【讨论】:

  • 这段代码看起来很有用,但有时程序只读取前 10 个字节或 12 个字节,并不希望读取所有这些
  • 是的,这只是一个示例,您可以更改它。重要的是Read函数的第三个参数必须总是小于等于BytesToRead
【解决方案2】:
猜你喜欢
  • 2011-11-22
  • 1970-01-01
  • 2013-01-24
  • 1970-01-01
  • 2021-12-01
  • 1970-01-01
  • 2020-12-27
  • 2018-03-06
  • 1970-01-01
相关资源
最近更新 更多