Search code examples
c#csvhelperformatexception

How do I find out, which columns has invalid value


I'm using CsvHelper to parse CSV files including type conversion, e.g. 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.


Solution

  • 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]