Is Streamreader reading a line that doesn’t exist?

Asked

Viewed 65 times

2

I want to read a CSV file and save it in 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, reaches line 194 with x values (supposedly the last line of the file and then reads another line (195) that does not exist and does not have any kind of values (null). I tried to fix it by opening the CSV file with Notepad and I checked that there was an extra line with nothing and deleted and saved and after this it should work and 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);
   }
  • I already edited, obg.

1 answer

7


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

That should work:

string line;

while ((line = sr.ReadLine()) != null) //Lê a linha e já checa se ela é nula
{
    // demais operações
}
  • Only now I had time to come here I tested what I said but now gave another error related to the array I just didn’t realize?

  • http://prntscr.com/ki96yn

  • You are reading the line 2 times. Remove line 46 q should work. @Jonas

  • http://prntscr.com/ki9feu -- I tried it but without success, I don’t understand why he gave this error supposedly everything seems to be fine.

  • This exception indicates that you are trying to access a position of the array that does not exist. Basically it is because you are giving Split on the line and trying to access the second value, but it only has 1.

  • I’ve seen what it was, the split should be ; instead of , and so it already reads the values well, but still I have 1 http://prntscr.com/kibwdx error.

  • Assetid are integer values but it’s reading the header that is string and I think it’s conflicting so there’s some way to make it better?

  • @Jonas Your original question has already been answered. If the answer has helped you, mark it as correct. If you have other questions, please ask another question.

Show 3 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.