Last active
August 29, 2015 14:27
-
-
Save versocode/c39783b15800158211c4 to your computer and use it in GitHub Desktop.
From http://stackoverflow.com/questions/398378/get-last-10-lines-of-very-large-text-file-10gb-c-sharp/398512#398512 read last n lines of file
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
public static string ReadEndTokens(string path, Int64 numberOfTokens, Encoding encoding, string tokenSeparator) { | |
int sizeOfChar = encoding.GetByteCount("\n"); | |
byte[] buffer = encoding.GetBytes(tokenSeparator); | |
using (FileStream fs = new FileStream(path, FileMode.Open)) { | |
Int64 tokenCount = 0; | |
Int64 endPosition = fs.Length / sizeOfChar; | |
for (Int64 position = sizeOfChar; position < endPosition; position += sizeOfChar) { | |
fs.Seek(-position, SeekOrigin.End); | |
fs.Read(buffer, 0, buffer.Length); | |
if (encoding.GetString(buffer) == tokenSeparator) { | |
tokenCount++; | |
if (tokenCount == numberOfTokens) { | |
byte[] returnBuffer = new byte[fs.Length - fs.Position]; | |
fs.Read(returnBuffer, 0, returnBuffer.Length); | |
return encoding.GetString(returnBuffer); | |
} | |
} | |
} | |
// handle case where number of tokens in file is less than numberOfTokens | |
fs.Seek(0, SeekOrigin.Begin); | |
buffer = new byte[fs.Length]; | |
fs.Read(buffer, 0, buffer.Length); | |
return encoding.GetString(buffer); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment