4

I'm using File.ReadLines().ToList() to read a regular text file into a List<string>.

The text file has 2 blank lines, like so ('View all characters' enabled in notepad++ for clarity):

enter image description here

Example code:

List<string> lines = null;
try{
    lines = File.ReadLines("C:\path\to\file.txt").ToList();
}catch(Exception e){
    //code here to handle e
}
Console.WriteLine(lines.Count.ToString());

Prints "1" to console.

My question is, why does my list that is generated by File.ReadLines().ToList() only have a Count of 1 when the file has 2 lines? Is a blank line at the end of the file just discarded by default? (it seems so)

Joshua Schlichting
  • 3,110
  • 6
  • 28
  • 54
  • 5
    The last 'line' is missing both content and its terminator, so it is not a line – TaW May 03 '19 at 16:12
  • 8
    It has only one blank line. Your editor thinks it is a good idea to allow you to put the caret past the end-of-file. Make it much easier to append more text. – Hans Passant May 03 '19 at 16:12
  • Say it ain't so! I'd expect more precision from a tool like Notepad++! – Joshua Schlichting May 03 '19 at 16:13
  • 1
    If you really want to see what's inside of a file try viewing it with a hex editor. – Selman Genç May 03 '19 at 16:13
  • 1
    Wow, opened it up with `vim` in WSL and sure enough, there isn't a second line. I learned something new today. Thanks so much for the input, everyone. @HansPassant, please respond with your answer, and I'll happily accept! – Joshua Schlichting May 03 '19 at 16:16
  • What's with the votes to close? It's a valid question/issue that others may run into in the future. Notepad++ is a widely used tool in the programming community. – Joshua Schlichting May 03 '19 at 16:46

1 Answers1

2

Thanks to Hans Passant for the answer. I was hoping he'd post it here, but I'm going to go ahead and do it now, as it looks like this question is very close to being closed (not sure why???) and I think this could help others in the future.

Answer: Notepad++ is showing a 2nd line that doesn't actually exist in the file. By opening the file with vim in WSL, I was able to see that there is one (1) line in the file, and no more than that.

enter image description here

Joshua Schlichting
  • 3,110
  • 6
  • 28
  • 54
  • I can't address what triggered a down vote without a comment or critique of some sort. Also, this really seems to be the only answer. I'm not sure how I could make this any better. – Joshua Schlichting May 07 '19 at 15:42