Chakra
Chakra

Reputation: 2557

Ambiguous Newline behavior in StreamReader

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.

Upvotes: 1

Views: 2872

Answers (3)

Dour High Arch
Dour High Arch

Reputation: 21712

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 your StreamReader 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.

Upvotes: 1

Austin Salonen
Austin Salonen

Reputation: 50225

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)

Upvotes: 0

BarrettJ
BarrettJ

Reputation: 3431

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.

Upvotes: 4

Related Questions