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

Unless you have fixed sized lines, you need to read every line until you reach the line you want. Although, you don't need to store each line, just discard it if it's not the line you desire.

Edit:

As mentioned, it would also be possible to seek in the file if the line lengths were predictable -- that is to say you could apply some deterministic function to transform a line number into a file position.


.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();
   }
}

If each line is a fixed length then you can open a Stream around it, seek (bytes per line) * n into the file and read your line from there.

using( Stream stream = File.Open(fileName, FileMode.Open) )
{
    stream.Seek(bytesPerLine * (myLine - 1), SeekOrigin.Begin);
    using( StreamReader reader = new StreamReader(stream) )
    {
        string line = reader.ReadLine();
    }
}

Alternatively you could just use the StreamReader to read lines until you found the one you wanted. That way's slower but still an improvement over reading every single line.

using( Stream stream = File.Open(fileName, FileMode.Open) )
{
    using( StreamReader reader = new StreamReader(fileStream) )
    {
        string line = null;
        for( int i = 0; i < myLineNumber; ++i )
        {
            line = reader.ReadLine();
        }
    }
}

No unfortunately there is not. At the raw level files do not work on a line number basis. Instead they work at a position / offset basis. The root filesystem has no concept of lines. It's a concept added by higher level components.

So there is no way to tell the operating system, please open file at line blah. Instead you have to open the file and skip around counting new lines until you've passed the specified number. Then store the next set of bytes into an array until you hit the next new line.