C# System.IO.IOException错误

C# System.IO.IOException错误,c#,exception,io,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

我写了一个从串口读取数据的程序。在安装了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);
如何解决此问题?

可能会有帮助:

但是我还没有测试过它。

可能会有帮助:


但是我还没有对它进行测试。

看起来您读取的字节数比端口传输的字节数要多,您应该检查
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);
}

看起来您读取的字节数比端口传输的字节数要多,您应该检查
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);
}

请添加有关此异常的更多详细信息。了解exat信息将对我们有很大帮助。还有,这些都是你的代码吗?你也在使用一些非.NET库吗?请阅读2个人需要取消他们的投票权。。。这个问题,就目前而言,不可能对其他人有用。是的,我确信这个端口很可能不一样。我是说,第一台机器上有COM1,另一台机器上有COM2。无论如何:请检查你的文章标题,以及正文。。可能你指的不是“另一个程序”,而是“另一台机器”,还有关于异常的更多细节,例如异常对象的ToString()方法的转储。请添加关于异常的更多细节。了解exat信息将对我们有很大帮助。还有,这些都是你的代码吗?你也在使用一些非.NET库吗?请阅读2个人需要取消他们的投票权。。。这个问题,就目前而言,不可能对其他人有用。是的,我确信这个端口很可能不一样。我是说,第一台机器上有COM1,另一台机器上有COM2。无论如何:请检查你的文章标题,以及正文。。可能你指的不是“另一个程序”,而是“另一台机器”,还有关于异常的更多细节,例如异常对象的ToString()方法的转储。这段代码很有用,但有时程序只读取前10个字节或12个字节,不希望读取所有字节是的,这只是一个示例,你可以改变它。重要的是,Read函数的第三个参数必须始终小于或等于ByTestOreAd。这段代码很有用,但有时程序只读取前10个字节或12个字节,并不希望读取所有字节。是的,这只是一个示例,您可以更改它。重要的是Read函数的第三个参数必须始终小于或等于BytesToRead