2017-10-06 66 views
0

CSV文件中缺少字段時,會引發異常。當某個字段丟失時,我寧願映射另一個值(如空字符串)。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(); 

如何更改該映射使得當映射字段缺失,也可以與另一種表達取代?

回答

1

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

你有展示MissingFieldFound任何使用的例子嗎?那些我發現只是將其設置爲空。 –

+1

我會在答案中舉個例子。 –

相關問題