c# how do I count lines in a textfile

The method you posted isn't particularly good. Lets break this apart:

// new StreamReader("file.txt").ReadToEnd().Split(new char[] {'\n'}).Length
//     becomes this:
var file = new StreamReader("file.txt").ReadToEnd(); // big string
var lines = file.Split(new char[] {'\n'});           // big array
var count = lines.Count;

You're actually holding this file in memory twice: once to read all the lines, once to split it into an array. The garbage collector hates that.

If you like one liners, you can write System.IO.File.ReadAllLines(filePath).Length, but that still retrieves the entire file in an array. There's no point doing that if you aren't going to hold onto the array.

A faster solution would be:

int TotalLines(string filePath)
{
    using (StreamReader r = new StreamReader(filePath))
    {
        int i = 0;
        while (r.ReadLine() != null) { i++; }
        return i;
    }
}

The code above holds (at most) one line of text in memory at any given time. Its going to be efficient as long as the lines are relatively short.


Well, the problem with doing this is that you allocate a lot of memory when doing this on large files.

I would rather read the file line by line and manually increment a counter. This may not be a one-liner but it's much more memory-efficient.

Alternatively, you may load the data in even-sized chunks and count the line breaks in these. This is probably the fastest way.


If you're looking for a short solution, I can give you a one-liner that at least saves you from having to split the result:

int i = File.ReadAllLines("file.txt").Count;

But that has the same problems of reading a large file into memory as your original. You should really use a streamreader and count the line breaks as you read them until you reach the end of the file.

Tags:

C#