Search code examples
c#csvcsvhelper

How to find out more details on CsvHelper.TypeConversion.CsvTypeConverterException?


I am trying to import CSV files with the following code:

using CsvHelper;
using CsvHelper.Configuration;
\\\ ...
try
  {
     var csv = new CsvReader(csvReader, new CsvConfiguration { 
        HasHeaderRecord = false, Delimiter = ";" });
     records = csv.GetRecords<FileDataContainerDisplay>().ToList();
   }
catch (Exception)
   {
      throw new FileFormatException();
}

The code fails with

Exception thrown: 'CsvHelper.TypeConversion.CsvTypeConverterException' in CsvHelper.dll

The curious thing is that the code used to work with files of the following kind:

Date;CurveName;Gridpoint;Timebase;Value
1.1.1900 00:00:00;A;1;1;0.12
1.1.1900 00:00:00;A;1;2;0.23
1.1.1900 00:00:00;A;1;3;0.34
...

May anybody guide me where to find more details on which type conversion failed exactly?

By the way, the definition of FileFormatException is rather boring:

public class FileFormatException : Exception
{ }

References


Solution

  • It looks like the problem is your configuration doesn't match your file. Your configuration says there is no header record, but your file appears to have a header record, so it is trying to read the word "Date" as a DateTime. When I look at the inner exception, I get more information.

    The string was not recognized as a valid DateTime. There is an unknown word starting at index 0.
    

    You should include the innerException with your FileFormatException class.

    public class FileFormatException : Exception
    {
        public FileFormatException(string message, Exception innerException) : base(message, innerException)
        {
        }
    }
    
    catch (Exception e)
    {
       throw new FileFormatException("Error message", e);
    }