object reference not set as instance of a string object []. split (char) [duplicate]

1

I have this code

StreamReader productosfile;
string linea;
string[] corte = new string[6];
productosfile = File.OpenText("productos.txt");
if (File.Exists("productos.txt"))
{
    do
    {
        linea = productosfile.ReadLine();
        corte = linea.Split('|');
        Producto producto = new Producto(corte[0], 
        Convert.ToInt32(corte[1]),
        DateTime.Parse(corte[2]), Convert.ToInt32(corte[3]),
        Convert.ToDecimal(corte[4]), corte[5], corte[6]);
        productos.Add(producto);

     } while (linea != null);
}

and I missed that error here corte = linea.Split('|') , before I had them without the new, and look in forums and said that this error was for not instantiating the class, now that instancio because it remains pass?

note: when setting an exception control, the exception is thrown but the code does what I want, reads the txt cuts the lines instance the product class and adds it perfectly to the list. But it still bothers me that this error is still showing

    
asked by Marcel Salazar 06.09.2018 в 02:17
source

1 answer

2

Very good, I put the code with some comments of the errors that I found

StreamReader productosfile;
string linea;
string[] corte;//No es necesario inicializar nada ya que posteriormente le asignas un nuevo objeto.

if (File.Exists("productos.txt"))//La comprobación de si existe el fichero debes hacerla antes de intentar abrirlo para lectura.
{
     productosfile = File.OpenText("productos.txt");
     while(!productosfile.EndOfStream) //Con este while iteramos hasta el final del archivo y evita la excepción que te estaba dando intentando leer mas datos cuando no los tienes en el fichero.
     {
         linea = productosfile.ReadLine();
         corte = linea.Split('|');
         Producto producto = new Producto(corte[0],
                        Convert.ToInt32(corte[1]),
                        DateTime.Parse(corte[2]), Convert.ToInt32(corte[3]),
                        Convert.ToDecimal(corte[4]), corte[5], corte[6]);
         productos.Add(producto);

      } 
}

Greetings, and any questions asked in the comments.

    
answered by 06.09.2018 / 08:12
source