Quote:
Hi I need to select a file with a window and read last line of the selected file.
If file is small, just reading the file is an OK solution, if file is huge, memory footprint will be huge too, and this can be a problem.
There is another approach using low level file functions
Those functions allow you to know the file length, seek to position and read/write from the position.
Say that last line is within last 100 chars of end of file:
open file
get length
seek to length-100 from beginning
read from position
FileStream.Seek(Int64, SeekOrigin) Method (System.IO) | Microsoft Docs[
^]
Sample code:
using System;
using System.IO;
public class FSSeek
{
public static void Main()
{
long offset;
int nextByte;
using (FileStream fs = new FileStream(@"c:\temp\alphabet.txt", FileMode.Open, FileAccess.Read))
{
for (offset = 1; offset <= fs.Length; offset++)
{
fs.Seek(-offset, SeekOrigin.End);
Console.Write(Convert.ToChar(fs.ReadByte()));
}
Console.WriteLine();
fs.Seek(20, SeekOrigin.Begin);
while ((nextByte = fs.ReadByte()) > 0)
{
Console.Write(Convert.ToChar(nextByte));
}
Console.WriteLine();
}
}
}