Parsing CSV files in C#, with header

后端 未结 17 1634
悲哀的现实
悲哀的现实 2020-11-21 06:57

Is there a default/official/recommended way to parse CSV files in C#? I don\'t want to roll my own parser.

Also, I\'ve seen instances of people using ODBC/OLE DB to

17条回答
  •  余生分开走
    2020-11-21 07:14

    Here is a short and simple solution.

                    using (TextFieldParser parser = new TextFieldParser(outputLocation))
                     {
                            parser.TextFieldType = FieldType.Delimited;
                            parser.SetDelimiters(",");
                            string[] headers = parser.ReadLine().Split(',');
                            foreach (string header in headers)
                            {
                                dataTable.Columns.Add(header);
                            }
                            while (!parser.EndOfData)
                            {
                                string[] fields = parser.ReadFields();
                                dataTable.Rows.Add(fields);
                            }
                        }
    

提交回复
热议问题