2016-07-28 73 views
0

我在以前的桌面應用程序中使用SerialPort類,我用下面的方法來讀取的SerialPort什麼等同於Windows 10應用程序中的serialPort.ReadExisting()?

響應
var response = serialPort.ReadExisting(); 

我現在用下面的方法實現在Windows 10應用程序一樣的東西

public static async Task<string> ReadAsync(CancellationToken cancellationToken,DataReader dataReaderObject) 
     { 
      string response = string.Empty; 
      try 
      { 
       var flag = false; 
       Task<UInt32> loadAsyncTask; 
       uint readBufferLength = 1024; 
       cancellationToken.ThrowIfCancellationRequested(); 
       dataReaderObject.InputStreamOptions = InputStreamOptions.Partial; 
       loadAsyncTask = dataReaderObject.LoadAsync(readBufferLength).AsTask(); 

       UInt32 bytesRead = await loadAsyncTask; 
       if (bytesRead > 0) 
       { 
        byte[] bytes = new byte[bytesRead]; 
        dataReaderObject.ReadBytes(bytes); 
        //response = Encoding.ASCII.GetString(bytes); 
        // response = Convert.ToString(bytes); 
        response= ASCIIEncoding.ASCII.GetString(bytes); 
       } 
      } 
      catch (Exception ex) 
      { 
       response = string.Empty; 
      } 
      return response; 
     } 

但是,看起來我正在以不同的編碼格式獲得響應。 當我在記事本++複製這兩個響應時,我發現以下區別:

enter image description here 這裏發生了什麼問題? 什麼等效於Windows 10應用程序中的serialPort.ReadExisting()?

+0

如果您可以粘貼舊版SerialPort代碼,這將有所幫助。你發送什麼字節? – Jackie

回答

0

SerialPort.ReadExisting Method()返回流和SerialPort對象爲字符串的內部緩衝器中的內容,因此,相當於ReadExisting()在Windows 10應用程式應DataReader.ReadString | readString method

但可以使用DataReader.ReadBytes | readBytes method,問題是如何將字節數組轉換爲字符串。這裏的字節使用UINT8編碼,這是可能的,你可以得到的字符串是這樣的:

Encoding.UTF8.GetString(bytes); 

你可以參考一個日本人blog,寫入ASCII編碼的數據,但仍然需要閱讀的UTF8。

相關問題