c # scroll txt from bottom to top

3

I have to go through a txt file but in the opposite direction to the usual, it would normally be something like this:

 using (var origen = new StreamWriter(rutaOrigen + "x.txt", 
 true, System.Text.Encoding.Default))
 {
      while ((lineaOrigen = origen.ReadLine()) != null)
      {
             //lineaOrigen es la linea del txt
      }
 {

But in this case I need to go from bottom to top ...

I can not save it in an array because the txt is too heavy

    
asked by Luis Gutierrez 31.05.2018 в 12:43
source

1 answer

3

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.

    
answered by 31.05.2018 / 18:14
source