检测文件的每一行如何以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 来获取每个字符并检查行终止符。您还必须跟踪是否看到回车符,以便在看到换行符时知道您是在处理 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,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;
}

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...