Parsing CSV files in C#, with header

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

    CsvHelper (a library I maintain) will read a CSV file into custom objects.

    var csv = new CsvReader( File.OpenText( "file.csv" ) );
    var myCustomObjects = csv.GetRecords();
    

    Sometimes you don't own the objects you're trying to read into. In this case, you can use fluent mapping because you can't put attributes on the class.

    public sealed class MyCustomObjectMap : CsvClassMap
    {
        public MyCustomObjectMap()
        {
            Map( m => m.Property1 ).Name( "Column Name" );
            Map( m => m.Property2 ).Index( 4 );
            Map( m => m.Property3 ).Ignore();
            Map( m => m.Property4 ).TypeConverter();
        }
    }
    

    EDIT:

    CsvReader now requires CultureInfo to be passed into the constuctor (https://github.com/JoshClose/CsvHelper/issues/1441).

    Example:

    var csv = new CsvReader(File.OpenText("file.csv"), System.Globalization.CultureInfo.CurrentCulture);
    

提交回复
热议问题