Search code examples
c#streamreader

Detect how each line of a file ends in C#


Is it possible to loop for each line in a file and check how it ends (LF / CRLF):

using(StreamReader sr = new StreamReader("TestFile.txt")) 
{
    string line;
    while ((line = sr.ReadLine()) != null) 
    {
        if (line.contain("\r\n") 
        {
            Console.WriteLine("CRLF");
        }
        else if (line.contain("\n") 
        {
            Console.WriteLine("LF");
        }
    }
}

Solution

  • You'll have to use Read to get each character and check for the line terminators. You'll also have to keep track if you've seen a carriage return so you'll know if you're dealing with a CRLF or just a LF when you see a line feed. And you'll have to check for a trailing CR after the loop is done.

    using(StreamReader sr = new StreamReader("TestFile.txt")) 
    {
        bool returnSeen = false;
        while (sr.Peek() >= 0) 
        {
            char c = sr.Read();
            if (c == '\n')
            {
                Console.WriteLine(returnSeen ? "CRLF" : "LF");
            }
            else if(returnSeen)
            {
                Console.WriteLine("CR");
            }
    
            returnSeen = c == '\r';
        }
    
        if(returnSeen) Console.WriteLine("CR");
    }
    

    Note you can construct the lines from the characters you read and you can change this to use the overload of Read that read into a buffer and search the result for the line terminators for better performance.