CsvHelper: Replace missing Csv field with another expression?

主宰稳场 提交于 2019-12-12 18:04:27

问题


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?


回答1:


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. );
};


来源:https://stackoverflow.com/questions/46605569/csvhelper-replace-missing-csv-field-with-another-expression

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!