StreamReader is reading a line that does not exist?

2

I want to read a CSV file and save it to a table, but for some reason it still gives the following error:

  

System.NullReferenceException: 'Object reference not set to an instance of an object.'

     

line was null.

I already ran the debug and noticed that it is reading a line that does not exist, for example, it arrives at line 194 with x values (supposedly the last line of the file and then reads another line (195) that does not exist and I did not have any kind of values (null) I tried to fix it by opening the CSV file with Notepad and checked that there was an extra line with nothing and I deleted and saved and after that it should work and it is not.

Here is my code:

using (StreamReader sr = new streamReader(@"PATH"))
{
   var datatable = new DataTable();
   datatable.Columns.Add("PowerPlantId", typeof(string));
   datatable.Columns.Add("AssetId", typeof(int));
   string line;

   line = sr.ReadLine();
   if (line != null)
   {
      do
      {
         line = sr.ReadLine();
         System.Diagnostics.Debug.WriteLine(line + "\n");
         string[] lineitems = line.Split(",");
         DataRow dr = datatable.NewRow();
         dr["PowerPlantId"] = lineitems[0];
         dr["AssetId"] = lineitems[1];
         datatable.Rows.Add(dr);
      } while (line != null);
   }
    
asked by anonymous 12.08.2018 / 22:58

1 answer

7

What is happening is that you are trying to do all operations on the line and then check if it is null, which does not make much sense.

This should work:

string line;

while ((line = sr.ReadLine()) != null) //Lê a linha e já checa se ela é nula
{
    // demais operações
}
    
13.08.2018 / 02:41