2

I would like to count number of lines in a file based on crlf (0D0A) count. My current code only counting the number of lines based on cr (0D). Can anybody give suggestion ?

public static int Countline(string file)
{
    var lineCount = 0;
    using (var reader = File.OpenText(file))
    {
        while (reader.ReadLine() != null)
        {
            lineCount++;
         }
    }
    return lineCount;
}
Garf365
  • 3,619
  • 5
  • 29
  • 41
  • 1
    probably duplicate: http://stackoverflow.com/questions/6655246/how-to-read-text-file-by-particular-line-separator-character – Bogdan Kuštan Jul 04 '16 at 07:40
  • Convert it to byte array using proper encoding. Then find any CR LF (0x0D 0x0A) using for loop. –  Jul 04 '16 at 07:43
  • you could use String.Split `foo.Split(new [] {Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries).Length;` – Nitro.de Jul 04 '16 at 07:48
  • not a duplicate. most only search for either /r or /n. i need to search both together not seperated. – jejakakhai Jk Jul 04 '16 at 08:18

3 Answers3

0

Usage:

Countline("text.txt", "\r\n");

Method:

public static int Countline(string file, string lineSeperator)
{
    string text = File.ReadAllText(file);

    return System.Text.RegularExpressions.Regex.Matches(text, lineSeperator).Count;
}
Zein Makki
  • 29,485
  • 6
  • 52
  • 63
  • this is a good step however have memory constrain as it first read all line in file. I have thousand of data in one file. – jejakakhai Jk Jul 04 '16 at 07:54
0
string content = System.IO.File.ReadAllText( fileName );
int numMatches = content.Select((c, i) => content.Substring(i)).Count(sub => sub.StartsWith(Environment.NewLine));

Note I'm using Environment.NewLine for line endings but you can replace with the whole string if you prefer.

LordWilmore
  • 2,829
  • 2
  • 25
  • 30
0
public int CountLines(string Text)
{
    int count = 0;
    foreach (ReadOnlySpan<char> _ in Text.AsSpan().EnumerateLines())
    {
        count++;
    }

    return count;
}

Benchmark:
Benchmark

Markus Meyer
  • 3,327
  • 10
  • 22
  • 35