Dealing with commas in a CSV file

后端 未结 27 2797
傲寒
傲寒 2020-11-21 06:53

I am looking for suggestions on how to handle a csv file that is being created, then uploaded by our customers, and that may have a comma in a value, like a company name.

27条回答
  •  长发绾君心
    2020-11-21 07:07

    There is a library available through nuget for dealing with pretty much any well formed CSV (.net) - CsvHelper

    Example to map to a class:

    var csv = new CsvReader( textReader );
    var records = csv.GetRecords();
    

    Example to read individual fields:

    var csv = new CsvReader( textReader );
    while( csv.Read() )
    {
        var intField = csv.GetField( 0 );
        var stringField = csv.GetField( 1 );
        var boolField = csv.GetField( "HeaderName" );
    }
    

    Letting the client drive the file format:
    , is the standard field delimiter, " is the standard value used to escape fields that contain a delimiter, quote, or line ending.

    To use (for example) # for fields and ' for escaping:

    var csv = new CsvReader( textReader );
    csv.Configuration.Delimiter = "#";
    csv.Configuration.Quote = ''';
    // read the file however meets your needs
    

    More Documentation

提交回复
热议问题