2

To read the first line of a .txt file in a wpf application, we can use this line of code:

string line1 = File.ReadLines("MyFile.txt").First(); // gets the first line

But now, how could i read just the second line of my file?

Clemens
  • 123,504
  • 12
  • 155
  • 268
Mot Franc
  • 157
  • 2
  • 4
  • 13
  • 1
    `File.ReadLines("MyFile.txt").Take(2).Last()`; `File.ReadLines("MyFile.txt").Skip(1).First()`;... – FoggyFinder Dec 11 '17 at 21:05
  • `File.ReadLines("MyFile.txt").Skip(1).FirstOrDefault();` – trailmax Dec 11 '17 at 21:05
  • `File.ReadLines("MyFile.txt").Skip(1).Take(1)` preserves the enumerable type. That makes the code more refactorable. – Enigmativity Dec 11 '17 at 21:08
  • 1
    @Mahmoud - `System.String` has a split function already. – Enigmativity Dec 11 '17 at 21:09
  • 2
    @Mahmoud - Just as a learning point for you, one of the disadvantages with the answer you had posted was requiring reading the entire file, which could be 100,000+ lines, [ReadLines](https://msdn.microsoft.com/en-us/library/dd383503(v=vs.110).aspx) is an IEnumerable that does not require loading the entire file. then splitting the lines and then finding the second line. – pstrjds Dec 11 '17 at 21:15
  • 1
    I didn't know that! Thanks @pstrjds for mentioning this! Reading the official documentation reveal things that one didn't notice. Just like this small but important detail. It was stupid answer indeed! – Rickless Dec 11 '17 at 21:18
  • 1
    While I do not expect SO to have questions for every possible "first,second, third, forth,..." apparently at least "second" is answered - https://www.bing.com/search?q=c%23+linq+second gives https://stackoverflow.com/questions/3701135/linq-selecting-second-item-in-ienumerable, – Alexei Levenkov Dec 11 '17 at 22:13

1 Answers1

10

Use Skip(1) to read the second line. Use FirstOrDefault() to avoid an error when the file is empty, or has only one line:

var line2 = File.ReadLines("MyFile.txt").Skip(1).FirstOrDefault();
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523