StreamReader 中不明确的换行行为
当我使用 StreamWriter.WriteLine 写入时,它将 CRLF 添加到字符串并将其发送(到串行端口)。
当我使用 StreamReader.ReadLine 在同一个 C# 程序中读取字符串并使用如下所示的数据时,它仅读取第一个 (char)13.ToString() 表示的第一个 CR,而不是 (char) 表示的 CRLF 13.ToString() + (char)10.ToString() 组合。
string messageHeader = ((char)2).ToString() +
@"1H|\^&|REMISOL|P|1|20010212161505SS" +
((char)13).ToString() +
((char)3).ToString() +
"E5" +
((char)13).ToString() +
((char)10).ToString();
我如何让它读取到位于末尾的 CRLF 块,而不是停在 CR 处?
谢谢。
When i write using StreamWriter.WriteLine, it adds CRLF to the string and sends it (to the SerialPort).
When i read a string in the same C# program using StreamReader.ReadLine with data like below, it only reads upto the first CR represented by the first (char)13.ToString(), not the CRLF that is represented by the (char)13.ToString() + (char)10.ToString() combination.
string messageHeader = ((char)2).ToString() +
@"1H|\^&|REMISOL|P|1|20010212161505SS" +
((char)13).ToString() +
((char)3).ToString() +
"E5" +
((char)13).ToString() +
((char)10).ToString();
How do i make it read upto the CRLF block, which is right at the end, and not stop at the CR ?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
StreamReader.ReadLine 的文档说明: 行定义为字符序列,后跟换行符 ("\n")、回车符 ("\r") 或回车符后紧跟换行符 ("\r") \n")
您需要使用读取并读取,直到手动遇到 \r\n。
StreamReader.ReadLine's documentation notes: A line is defined as a sequence of characters followed by a line feed ("\n"), a carriage return ("\r") or a carriage return immediately followed by a line feed ("\r\n")
You'll need to use Read and read until you encounter \r\n manually.
StreamReader.ReadLine()
最多读取(但不包括)下一个 CR、LF 或 CRLF。我刚刚在您的示例代码上尝试过它,它返回 2 行,读取但不包括尾随的 CRLF。如果这不是您所看到的,则您的 StreamReader 存在一些不同,您必须向我们展示重复该问题的完整代码。这是否是您所看到的,而不是您想要的,您必须更详细地描述问题。
StreamReader.ReadLine()
reads up to, but does not include, the next CR, LF, or CRLF. I just tried it on your sample code and it returns 2 lines, reading up to and not including the trailing CRLF. If this is not what you are seeing, there is something different about yourStreamReader
and you will have to show us complete code that duplicates the problem.Is this is what you are seeing, and it is not what you want, you will have to describe the problem in more detail.
如果您使用的是 SerialPort 类 ,您可以手动设置 NewLine 属性 到您需要的任何内容(默认情况下是 LF(字符 10))
If you're using the SerialPort class, you can manually set the NewLine property to whatever you need (it is LF (char 10) by default, though)