Search code examples
c#automappercsvhelper

CsvHelper: Replace missing Csv field with another expression?


When a field is missing in the CSV file, an exception is thrown. I'd rather map another value (such as empty string) when a field is missing.

Map(dest => dest.PatientID).Name("Patient ID");

CsvHelper.CsvMissingFieldException: 'Fields 'Patient ID' do not exist in the CSV file.'

If the configuration setting IgnoreReadingExceptions is used, no records are read into the results.

var csv = new CsvReader(sr);
csv.Configuration.RegisterClassMap<TMap>();
csv.Configuration.IgnoreReadingExceptions = true;
records = csv.GetRecords<TR>().ToList();

How can I change the mapping such that when the mapped field is MISSING, it can be replaced with another expression?


Solution

  • In 2.x you can do this:

    csv.Configuration.WillThrowOnMissingField = false;
    

    In 3.x you can do this:

    // Turn off.
    csv.Configuration.MissingFieldFound = null;
    
    
    // Log missing field.
    csv.Configuration.MissingFieldFound = ( headerNames, index, context ) =>
    {
        logger.WriteLine( $"Field with names ['{string.Join( "', '", headerNames )}'] at index '{index}' was not found. ");
    };