什么等同于Windows 10应用程序中的serialPort.ReadExisting()?

问题描述:

我在以前的桌面应用程序中使用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

SerialPort.ReadExisting Method()返回流和SerialPort对象为字符串的内部缓冲器中的内容,因此,相当于ReadExisting()在Windows 10应用程式应DataReader.ReadString | readString method

但可以使用DataReader.ReadBytes | readBytes method,问题是如何将字节数组转换为字符串。这里的字节使用UINT8编码,这是可能的,你可以得到的字符串是这样的:

Encoding.UTF8.GetString(bytes); 

你可以参考一个日本人blog,写入ASCII编码的数据,但仍然需要阅读的UTF8。