Parsing CSV files in C#, with header

后端 未结 17 1632
悲哀的现实
悲哀的现实 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

    In a business application, i use the Open Source project on codeproject.com, CSVReader.

    It works well, and has good performance. There is some benchmarking on the link i provided.

    A simple example, copied from the project page:

    using (CsvReader csv = new CsvReader(new StreamReader("data.csv"), true))
    {
        int fieldCount = csv.FieldCount;
        string[] headers = csv.GetFieldHeaders();
    
        while (csv.ReadNextRecord())
        {
            for (int i = 0; i < fieldCount; i++)
                Console.Write(string.Format("{0} = {1};", headers[i], csv[i]));
    
            Console.WriteLine();
        }
    }
    

    As you can see, it's very easy to work with.

提交回复
热议问题