Pregunta

Tengo un archivo (test.txt) que contiene " 1234567 " ;. Sin embargo, cuando intento leerlo en C # usando FileStream.Read, obtengo solo 0s (siete ceros en este caso). ¿Alguien podría decirme por qué? Estoy realmente perdido aquí.

Editar: Problema resuelto, operador de comparación incorrecto. Sin embargo, ahora está volviendo & Quot; 49505152535455 & Quot;

Editar 2: Listo. Para el registro, tuve que generar la variable byte como char .

using System;
using System.IO;

class Program
{
    static void Main()
    {

        FileStream fil = null;

        try
        {
            fil = new FileStream("test.txt", FileMode.Open,FileAccess.Read);

            byte[] bytes = new byte[fil.Length];
            int toRead = (int)fil.Length;
            int Read = 0;

            while (toRead < 0)
            {
                int n = fil.Read(bytes, Read, toRead);

                Read += n;
                toRead -= n;
            }

            //Tried this, will only return 0000000
            foreach (byte b in bytes)
            {
                Console.Write(b.ToString());
            }


        }
        catch (Exception exc)
        {
            Console.WriteLine("Oops! {0}", exc.Message);
        }
        finally
        {
            fil.Close();
        }


        Console.ReadLine();
    }
}
¿Fue útil?

Solución

Esta línea

while (toRead < 0)

se asegura de que nunca leas realmente. toRead será > = 0 antes del ciclo.

Luego vuelca la matriz de bytes que nunca se llenó.

Otros consejos

 foreach (byte b in bytes)
            {
                Console.Write(b.ToString());
            }

Este código es incorrecto. Está imprimiendo el valor de cadena del valor del byte. es decir, 49 para el ascii char '0', 50 para '1', etc.

Necesita mostrarlo como

Console.Write(new Char(b).toString());

while (toRead < 0) debería ser while (toRead > 0) (mayor que)

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top