Dev Dev - 1 year ago 80
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)

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

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

row.ItemArray = r.Split(line);


csv file

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 Source

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();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download