How do I read a specified line in a text file?

.NET 4.0 edit

Since .NET 4.0, it is possible to access a single line of a file directly. For instance, to access line 15:

string line = File.ReadLines(FileName).Skip(14).Take(1).First();

This will return only the line required


Since you can’t predict the location (can you?) of the i-th line in the file, you’ll have to read all previous lines too. If the line number is small, this can be more efficient than the ReadAllLines method.

string GetLine(string fileName, int line)
{
   using (var sr = new StreamReader(fileName)) {
       for (int i = 1; i < line; i++)
          sr.ReadLine();
       return sr.ReadLine();
   }
}

Leave a Comment