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.8, Visual Studio 2022, Windows 10
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");
}

Posted: March 19, 2023

Return to the snippets listing