Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# how do I count lines in a textfile

Tags:

c#

any problems with doing this?

int  i = new StreamReader("file.txt").ReadToEnd().Split(new char[] {'\n'}).Length
like image 406
Brad Avatar asked Jan 30 '09 18:01

Brad


4 Answers

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.

like image 102
Juliet Avatar answered Oct 11 '22 15:10

Juliet


That should do the trick:

using System.Linq;

....

int i = File.ReadLines(file).Count();
like image 44
dimaaan Avatar answered Oct 11 '22 16:10

dimaaan


Mayby this?

string file = new StreamReader("YourFile.txt").ReadToEnd();
string[] lines = file.Split('\n');
int countOfLines = lines.GetLength(0));
like image 42
Rinepim Avatar answered Oct 11 '22 16:10

Rinepim


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.

like image 22
Joel Coehoorn Avatar answered Oct 11 '22 15:10

Joel Coehoorn