Search code examples
c#streamreader

Reading a specific line with StreamReader


I have a problem with the stream reader. i want to read from a text file just one line.

I want a specific line, like the seventh line. and i don't know how to.

it's a function or something like that ? like file.ReadLine(number 7) ?


Solution

  • The simplest approach would probably be to use LINQ combined with File.ReadLines:

    string line = File.ReadLines("foo.txt").ElementAt(6); // 0-based
    

    You could use File.ReadAllLines instead, but that would read the whole file even if you only want an early one. If you need various different lines of course, it means you can read them in one go. You could write a method to read multiple specific lines efficiently (i.e. in one pass, but no more than one line at a time) reasonably easily, but it would be overkill if you only want one line.

    Note that this will throw an exception if there aren't enough lines - you could use ElementAtOrDefault if you want to handle that without any exceptions.