【问题标题】:Detect how each line of a file ends in C#检测文件的每一行如何以 C# 结尾
【发布时间】:2021-01-22 15:36:17
【问题描述】:

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

【问题讨论】:

  • ReadLine 将删除行终止符,因此您需要读取并检查行终止字符。
  • 你能给我一个例子吗?
  • 如果文件包含两种类型的行尾,你希望它如何处理?
  • 我会把它放在一个日志文件中,每一行都以它的结尾
  • @user2848242 I will put it in a log file, each line whith its end 会破坏日志文件的行

标签: c# streamreader


【解决方案1】:

您必须使用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 的重载并在结果中搜索行终止符以获得更好的性能。

【讨论】:

    【解决方案2】:

    你可以用这个代码:

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

    【讨论】:

      猜你喜欢
      • 2010-09-07
      • 2014-07-08
      • 2016-08-13
      • 2013-07-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多