1

This questions is really simple, and probably you .NET gurus now the answer =)

So here it comes... What is the proper way (.NET language independent to determine the number of lines (non-blank) exists in a text files without having to check until the line is empty (My current approach)?

Thanks in advance

3 Answers3

4

Borrowing from here:

var lineCount = 0;
using (var reader = File.OpenText(@"C:\file.txt"))
{
    while ((string line = reader.ReadLine()) != null)
    {
        if (line.Length > 0) lineCount++;
    }
}
Community
  • 1
  • 1
Foole
  • 4,754
  • 1
  • 26
  • 23
  • THis the approach i'm currently using –  Feb 16 '10 at 06:18
  • @Fladur your question doesn't explain this clearly. I don't think I deserve -1. – Foole Feb 16 '10 at 06:55
  • From my post: without having to check until the line is empty (My current approach)? You just copy pasted some code –  Feb 16 '10 at 20:22
  • 1
    Lesson learned. Don't try to help people who don't post code. – Foole Feb 16 '10 at 21:12
  • 1
    Fladur you asked for the appropiate way of reading the number of lines. cxfx gave you a 1-liner that loads the whole file into the memory at once which makes it unsuitable for larger files. Foole's answer on the other hand only uses the amount of memory equal to the longest line in the file which in almost all cases won't be noticeable. – Kasper Holdum Feb 16 '10 at 21:32
  • Btw, an even more efficient way to do this would be to read character by character checking for newlines and never build the line strings. – Foole Feb 16 '10 at 21:46
  • 1
    +1 ridiculous to downvote this, current approach wasn't given in the question. – Chris Fulstow Feb 16 '10 at 22:25
  • It's subjective, You are right, sorry, please edit something in your question so that I can remove my vote. –  Feb 16 '10 at 23:28
2
var path = @"C:\file.txt";
var lines = File.ReadAllLines(path);
var lineCount = lines.Count(s => s != "");

Or, slightly less readable, all in one go:

var lines = File.ReadAllLines(@"C:\file.txt").Count(s => s != "");
Chris Fulstow
  • 41,170
  • 10
  • 86
  • 110
  • 1
    ReadAllLines is very inefficient for large files as it reads the entire file in to memory. – Foole Feb 16 '10 at 06:57
  • @Foole @Qua That's true; however, the question asks for the 'proper' way, which would be different based of the size of file you're expecting. It's subjective. – Chris Fulstow Feb 16 '10 at 22:30
1

A file is read in as a stream, so you must read it all to determine what you are trying.

You could scan the bytes, or perform a ReadToEnd on the your FileReader to get the string representation, to find the Environment.NewLine instances and count them.

If you read the file into a string, you have the added benefit of being able to use the Regex classes to count the matches of your Environment.NewLine

EDIT I do like cxfx idea of using File.ReadAllLines and using the resultant Length

johnc
  • 39,385
  • 37
  • 101
  • 139