Parsing CSV files in C#, with header

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

    Another one to this list, Cinchoo ETL - an open source library to read and write multiple file formats (CSV, flat file, Xml, JSON etc)

    Sample below shows how to read CSV file quickly (No POCO object required)

    string csv = @"Id, Name
    1, Carl
    2, Tom
    3, Mark";
    
    using (var p = ChoCSVReader.LoadText(csv)
        .WithFirstLineHeader()
        )
    {
        foreach (var rec in p)
        {
            Console.WriteLine($"Id: {rec.Id}");
            Console.WriteLine($"Name: {rec.Name}");
        }
    }
    

    Sample below shows how to read CSV file using POCO object

    public partial class EmployeeRec
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
    
    static void CSVTest()
    {
        string csv = @"Id, Name
    1, Carl
    2, Tom
    3, Mark";
    
        using (var p = ChoCSVReader.LoadText(csv)
            .WithFirstLineHeader()
            )
        {
            foreach (var rec in p)
            {
                Console.WriteLine($"Id: {rec.Id}");
                Console.WriteLine($"Name: {rec.Name}");
            }
        }
    }
    

    Please check out articles at CodeProject on how to use it.

提交回复
热议问题