Skip to content

Instantly share code, notes, and snippets.

@Martyr2
Created October 11, 2017 02:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Martyr2/7cb82a89f84a98a43811478c7a4c0bd2 to your computer and use it in GitHub Desktop.
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.
/// <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