Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
245 views
in Technique[技术] by (71.8m points)

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("
") 
        {
            Console.WriteLine("CRLF");
        }
        else if (line.contain("
") 
        {
            Console.WriteLine("LF");
        }
    }
}
question from:https://stackoverflow.com/questions/65848130/detect-how-each-line-of-a-file-ends-in-c-sharp

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 == '
')
        {
            Console.WriteLine(returnSeen ? "CRLF" : "LF");
        }
        else if(returnSeen)
        {
            Console.WriteLine("CR");
        }

        returnSeen = c == '
';
    }

    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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...