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);
}