Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading last symbol from text file using C# [duplicate]

Tags:

c#

file-io

What is the most efficient way to read the last symbol or line of a large text file using C#?

like image 643
Ksice Avatar asked Feb 16 '23 01:02

Ksice


2 Answers

Assuming your text file is ASCII, this method will allow you to jump straight to the last character and avoid reading the rest of the file (like all the other answers given so far do).

using (FileStream stream = new FileStream(path, FileMode.Open, FileAccess.Read))
{
    stream.Seek(-1, SeekOrigin.End);
    byte b = (byte)stream.ReadByte();
    char c = (char)b;
}

If your program needs to handle multi-byte encodings, you might need to perform some complex logic, as shown is Skeet's answer. However, given that your case is restricted just to reading the last character, you can implement a simplified version specific to your expected encoding. The code below works for UTF-8 (which is the most popular encoding today). The Seek may land your reader in the middle of a preceding character, but the decoder will recover from this by the time it reads the last character.

FileInfo fileInfo = new FileInfo(path);
int maxBytesPerChar = Encoding.UTF8.GetMaxByteCount(1);
int readLength = Math.Min(maxBytesPerChar, (int)fileInfo.Length);

using (StreamReader reader = new StreamReader(path, Encoding.UTF8))
{
    reader.DiscardBufferedData();
    reader.BaseStream.Seek(-readLength, SeekOrigin.End);

    string s = reader.ReadToEnd();
    char c = s.Last();
}
like image 103
Douglas Avatar answered Feb 24 '23 11:02

Douglas


If the file is not too large, just read the lines and pick the last:

string lastLine = File.ReadLines("pathToFile").LastOrDefault(); // if the file is empty

So you get the last character in this way:

Char lastChar = '\0';
if(lastLine  != null) lastChar = lastLine.LastOrDefault();

File.ReadLines does not need to read all lines before it can start processsing, so it's cheap in terms of memory consumption.

Here is the more complicated way from J. Skeet: How to read a text file reversely with iterator in C#

like image 28
Tim Schmelter Avatar answered Feb 24 '23 11:02

Tim Schmelter