Dev Dev - 1 month ago 11
C# Question

First line is not imported into DataTable from csv

I am working on a application which exports a csv to a DataTable and for some reasons, DataTable is not populated with first line in csv after headers row

I have tried the following code

Regex r = new Regex(",(?=(?:[^\"]*\"[^\"]*\")*(?![^\"]*\"))");

StreamReader sr = new StreamReader(fileName);
string[] headers = sr.ReadLine().Split(',');
foreach (string header in headers)
{
dt.Columns.Add(header);
}

line = sr.ReadLine();
strArray = r.Split(line);


while ((line = sr.ReadLine()) != null)
{
row = dt.NewRow();


row.ItemArray = r.Split(line);
dt.Rows.Add(row);
}


sr.Dispose();


csv file

FirstName,LastName,Address
Sally, Whittaker,Houston
Belinda, Jameson,Austin
Jeff, Smith,Seattle


Headers are exported just fine but the line after headers isn't uploaded as follows
enter image description here

May I know if I am missing anything?

Answer

Remove ReadLine() outside the while loop because its first read's the first line then in while loop reading happening after that first line.

line = sr.ReadLine();