Get total number of non-blank lines from text file?
Asked Answered
F

1

10

I am using...

File.ReadLines(@"file.txt").Count();

...to find the total number of lines in the file. How can I do this, but ignore all blank lines?

Fanfani answered 2/3, 2014 at 23:42 Comment(0)
F
16

You can use String.IsNullOrWhiteSpace method with Count:

File.ReadLines(@"file.txt").Count(line => !string.IsNullOrWhiteSpace(line));

Or another way with All and char.IsWhiteSpace:

File.ReadLines(@"file.txt").Count(line => !line.All(char.IsWhiteSpace));
Ferree answered 2/3, 2014 at 23:42 Comment(1)
just as a variety, also line.Trim() != String.Empty would work, though probably not the best option.Cycad

© 2022 - 2024 — McMap. All rights reserved.