Using the property% co_of% of Position
you can achieve it and reading the file from the end to the beginning only obtaining part of the file using a FileStream
.
In the following example, it only loads 1KB of text from the file into memory. Decreasing the reading position of the file until it reaches position 0:
const int chunkSize = 1024; // Indica la cantidad de texto a leer, en es caso 1KB
using (var file = File.OpenRead("archivo.txt"))
{
// iniciamos la lectura en el ultimo 1KB del texto
file.Position = file.Length - chunkSize;
// restara la cantidad de recoridos en el archivo hasta
// que file.Position llegue a 0 que seria el inicio del archivo
int loopCount = 1;
int bytesRead;
var buffer = new byte[chunkSize];
while ((bytesRead = file.Read(buffer, 0, buffer.Length)) > 0)
{
loopCount++;
// aqui obtienes 1kb de texto almacenado en el buffer
// este seria el texto que procesarias
var texto = Encoding.UTF8.GetString(buffer);
ProcesarTexto(texto);
//si la posicion es 0(inicio del archivo), detenemos el while
if (file.Position >= 0)
break;
// por cada loop editamos la posIcion a leer. Eso lo hacemos restando al tamaño total del archivo por
// el chunkSize(cantidad de bytes a leer) menos el numero del recorrido
var nuevaPosicion = file.Length - (chunkSize * loopCount);
// Si la nueva posicion es menor a cero es porque ya este seria el penultimo loop.
if (nuevaPosicion <= 0)
{
// le asigmanos la posicion inicial del archivo
file.Position = 0;
// editamos el buffer para que solo lea el total restante de bytes
// y asi no incluya texto ya procesado
buffer = new byte[chunkSize - Math.Abs(nuevaPosicion)];
}
else
{
file.Position = nuevaPosicion;
}
}
}
Note that this solution does not take into account the encoding in which the file is written.