I'm using CsvHelper to parse CSV files including type conversion, eg to DateTime.
When the cell value has invalid format, I get
while (CsvReader.Read())
{
var record = CsvReader.GetRecord<TModel>();
csvReader.GetRecord<MyModel>(); //throws following exception:
// CsvHelper.ReaderException: 'An unexpected error occurred.'
// Inner Exception
//
// FormatException: The string 'a' was not recognized as a valid DateTime. There is an unknown word starting at index '0'.
How do I find the cell's HeaderName or MyModel's property, that has failed to parse.
You should add a try and in your catch you can get row and index using
int index = csvReader.Context.CurrentIndex; // zero based
int row = csvReader.Context.Row; // 1 based
Then you can get your field using headers record
csvReader.Context.HeaderRecord[index]
To add up on itdoesntwork, here is how I did it
catch (ReaderException e)
{
string notification = $"The field { e.ReadingContext.HeaderRecord[e.ReadingContext.CurrentIndex] } has the invalid value { e.ReadingContext.Record[e.ReadingContext.CurrentIndex] }";
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.