1

I'm using next code to count lines in a text i have. It's work fine but I don't want to count empty lines. How can I do it, but with saving the current code format?

var lineCount = 0;
using (var readerlines = File.OpenText(strfilename))
{
    while (readerlines.ReadLine() != null)
    {
        lineCount++;
    }
}
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
Coby Abutbul
  • 55
  • 1
  • 8

3 Answers3

4

You can try like this:

int lineCount = File.ReadLines(@"yourfile.txt")
                    .Count(line => !string.IsNullOrWhiteSpace(line));
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
2

Check if the line is not an empty string

var lineCount = 0;
string line = string.Empty;
using (var readerlines = File.OpenText(strfilename))
{
    while ((line = readerlines.ReadLine()) != null)
    {
        if (!line.Equals(string.Empty))
        {
            lineCount++;
        }   
    }
}
Guy
  • 46,488
  • 10
  • 44
  • 88
0

Or this:

string data = File.ReadAllText(strfilename);
string[] lines = data.Split(new char[] {'\n' }, StringSplitOptions.RemoveEmptyEntries);
int line_count = lines.Length;

In short:

int line_count = File.ReadAllText(strfilename).Split(new char[] {'\n' }, StringSplitOptions.RemoveEmptyEntries).Length;
i486
  • 6,491
  • 4
  • 24
  • 41