Created
October 11, 2017 02:51
-
-
Save Martyr2/7cb82a89f84a98a43811478c7a4c0bd2 to your computer and use it in GitHub Desktop.
Reads the Nth line from a text file. It will throw exceptions if the file has fewer lines or Nth line is negative.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <summary> | |
/// Reads the Nth line from the file specified by filepath. | |
/// </summary> | |
/// <param name="filepath">Path to the file to read</param> | |
/// <param name="linenumber">Line number of the line to return</param> | |
/// <returns>Returns Nth line</returns> | |
private String readLineNumber(String filepath, int linenumber) { | |
if (linenumber > 0) { | |
using (StreamReader reader = new System.IO.StreamReader(filepath)) { | |
var count = 1; | |
while (reader.Peek() >= 0) { | |
if (count == linenumber) { | |
return reader.ReadLine(); | |
} | |
reader.ReadLine(); | |
count++; | |
} | |
} | |
throw new Exception("File has fewer lines than line number specified."); | |
} | |
throw new Exception("Line number must be larger than 0"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment