簡體   English   中英

System.IO.IOException錯誤

[英]System.IO.IOException error

我編寫了一個從串行端口讀取的程序。 在安裝了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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM