Parsing CSV files in C#, with header

后端 未结 17 1691
悲哀的现实
悲哀的现实 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条回答
  •  旧时难觅i
    2020-11-21 07:23

    This code reads csv to DataTable:

    public static DataTable ReadCsv(string path)
    {
        DataTable result = new DataTable("SomeData");
        using (TextFieldParser parser = new TextFieldParser(path))
        {
            parser.TextFieldType = FieldType.Delimited;
            parser.SetDelimiters(",");
            bool isFirstRow = true;
            //IList headers = new List();
    
            while (!parser.EndOfData)
            {
                string[] fields = parser.ReadFields();
                if (isFirstRow)
                {
                    foreach (string field in fields)
                    {
                        result.Columns.Add(new DataColumn(field, typeof(string)));
                    }
                    isFirstRow = false;
                }
                else
                {
                    int i = 0;
                    DataRow row = result.NewRow();
                    foreach (string field in fields)
                    {
                        row[i++] = field;
                    }
                    result.Rows.Add(row);
                }
            }
        }
        return result;
    }
    

提交回复
热议问题