Stream read line

procma picture procma · Sep 15, 2014 · Viewed 14k times · Source

I have a stream reader line by line (sr.ReadLine()). My code counts the line-end with both line endings \r\n and/or \n.

        StreamReader sr = new System.IO.StreamReader(sPath, enc);

        while (!sr.EndOfStream)
        {
            // reading 1 line of datafile
            string sLine = sr.ReadLine();
            ...

How to tell to code (instead of universal sr.ReadLine()) that I want to count new line only a full \r\n and not the \n?

Answer

Andrey Korneyev picture Andrey Korneyev · Sep 15, 2014

It is not possible to do this using StreamReader.ReadLine. As per msdn:

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"). The string that is returned does not contain the terminating carriage return or line feed. The returned value is null if the end of the input stream is reached.

So yoг have to read this stream byte-by-byte and return line only if you've captured \r\n

EDIT

Here is some code sample

private static IEnumerable<string> ReadLines(StreamReader stream)
{
    StringBuilder sb = new StringBuilder();

    int symbol = stream.Peek();
    while (symbol != -1)
    {
        symbol = stream.Read();
        if (symbol == 13 && stream.Peek() == 10)
        {
            stream.Read();

            string line = sb.ToString();
            sb.Clear();

            yield return line;
        }
        else
            sb.Append((char)symbol);
    }

    yield return sb.ToString();
}

You can use it like

foreach (string line in ReadLines(stream))
{
   //do something
}