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

时间:2016-07-28 10:02:21

标签: c# encoding serial-port uwp windows-10-universal

我在之前的桌面应用程序中使用了SerialPort类,我使用以下方法从SerialPort读取响应

 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()?

1 个答案:

答案 0 :(得分:0)

SerialPort.ReadExisting Method ()以字符串形式返回SerialPort对象的流和内部缓冲区的内容,因此Windows 10应用中的ReadExisting()等效值应为DataReader.ReadString | readString method

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

Encoding.UTF8.GetString(bytes); 

您可以参考日语blog,它会写入ASCII编码数据但仍需要读取为UTF8。