Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 762
disassemble-number-5 Avatar asked Sep 13 '26 13:09

disassemble-number-5


1 Answers

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. ");
};
like image 59
Josh Close Avatar answered Sep 15 '26 02:09

Josh Close