检测文件的每一行如何以 C# 结尾

Detect how each line of a file ends in C#

是否可以循环文件中的每一行并检查它是如何结束的(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");
        }
    }
}

您必须使用 Read 来获取每个字符并检查行终止符。如果您看到了回车 return,您还必须保持跟踪,这样当您看到换行符时,您就会知道您是在处理 CRLF 还是只是 LF。并且您必须在循环完成后检查尾随 CR。

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");
}

请注意,您可以根据读取的字符构造行,您可以将其更改为使用 Read 的重载,读取缓冲区并在结果中搜索行终止符以获得更好的性能。

您可以使用此代码:

private const char CR = '\r';  
private const char LF = '\n';  
private const char NULL = (char)0;

public static long CountLines(Stream stream)  
{
    //Ensure.NotNull(stream, nameof(stream));

    var lineCount = 0L;

    var byteBuffer = new byte[1024 * 1024];
    var prevChar = NULL;
    var pendingTermination = false;

    int bytesRead;
    while ((bytesRead = stream.Read(byteBuffer, 0, byteBuffer.Length)) > 0)
    {
        for (var i = 0; i < bytesRead; i++)
        {
            var currentChar = (char)byteBuffer[i];

            if (currentChar == NULL) { continue; }
            if (currentChar == CR || currentChar == LF)
            {
                if (prevChar == CR && currentChar == LF) { continue; }

                lineCount++;
                pendingTermination = false;
            }
            else
            {
                if (!pendingTermination)
                {
                    pendingTermination = true;
                }
            }
            prevChar = currentChar;
        }
    }

    if (pendingTermination) { lineCount++; }
    return lineCount;
}