Read Nth Line from Text File

Description: Specify the text file and the Nth line number to read and it will return the line of text.
Tested Platform: .NET 4.0, Visual Studio 2010, Windows 7
Language: C#
// ReadLineNumber: reads the Nth line from the file specified by filepath.
// Requires System.IO namespace

private String readLineNumber(String filepath, int linenumber) {
    if (linenumber > 0) {
        if (File.Exists(filepath)) {
            using (StreamReader reader = new System.IO.StreamReader(filepath)) {
                var count = 1;

                // Peek to see if there is a line to be read.
                while (reader.Peek() >= 0) {
                    if (count == linenumber) {
                        return reader.ReadLine();
                    }
                    reader.ReadLine();
                    count++;
                }
            }
        }
        else { throw new Exception("File specified does not exist."); }

        throw new Exception("File has fewer lines than line number specified.");
    }
    throw new Exception("Line number must be larger than 0");
}

Submitted: January 13, 2013

Return to the snippets listing