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.
– Jonas