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 に答える