简体   繁体   中英

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 在此处输入图片说明

May I know if I am missing anything?

This is an extra ReadLine you are reading a line below but not using it at the end.

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

Remove these two lines before your "while" loop:

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

Not only both are useless but the first is also the cause of your issue.

'Hope this helps.

在while循环外删除ReadLine() ,因为它的第一读是第一行,然后在while循环中发生在第一行之后。

line = sr.ReadLine();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM