Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stream read line

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?

like image 428
procma Avatar asked Dec 20 '22 11:12

procma


2 Answers

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
}
like image 92
Andrey Korneyev Avatar answered Jan 03 '23 00:01

Andrey Korneyev


you cannot do it with ReadLine, but you can do instead:

stream.ReadToEnd().Split(new[] {"\r\n"}, StringSplitOptions.None)
like image 25
Enrico Sada Avatar answered Jan 03 '23 00:01

Enrico Sada