c# - CsvHelper:用另一个表达式替换缺失的 Csv 字段?

标签 c# automapper csvhelper

当 CSV 文件中缺少字段时,将引发异常。当一个字段丢失时,我宁愿映射另一个值(例如空字符串)。

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

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

如果使用配置设置 IgnoreReadingExceptions,则不会将任何记录读入结果。

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

如何更改映射,以便当映射字段缺失时,可以用另一个表达式替换它?

最佳答案

在 2.x 中你可以这样做:

csv.Configuration.WillThrowOnMissingField = false;

在 3.x 中你可以这样做:

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

关于c# - CsvHelper:用另一个表达式替换缺失的 Csv 字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46605569/

相关文章:

c# - HiddenField 始终为 NULL,来自 javascript

c# - CsvHelper - 异步读取流

c# - 如果对象成员没有值,如何为对象分配 null - automapper c#

asp.net - 有关使用字段子集的 View 模型和模型更新的最佳实践

asp.net - 使用 Mapper.Initialize() 进行多个映射

c# - CSV Helper 如何读取具有多个标题行的 csv 文件

c# - 将 CSV header 与 map 类进行比较

c# - Windows Phone 8.1 MapIcon 单击事件

c# - 如何打破 Parallel.ForEachAsync 循环,而不是取消它?

c# - app.config 中的自定义部分在 C# 中抛出错误