2

I have a TXT file to parse and I’m using the CsvHelper package to do so. The content of the file is:

 A; B; C; D; E; F; G; H
a;b;;2021-05-06;e;11:00;3;9

Note there’re spaces on the header line, before the column names ( A, B, etc.).

I’m using the following class to parse the CSV:

public class MyClass
{
    [Name(" A")]
    public string a { get; set; }

    [Name(" B")]
    public string b { get; set; }

    [Name(" C")]
    public string c { get; set; }

    [Name(" D")]
    public DateTime d { get; set; }

    [Name(" E")]
    public string e { get; set; }

    [Name(" F")]
    public TimeSpan f { get; set; }

    [Name(" G")]
    public string g { get; set; }

    [Name(" H")]
    public string h { get; set; }
}

and the following logic for the deserialization:

var reader = new CsvReader(myStreamReader, new CsvConfiguration(CultureInfo.InvariantCulture)
                {
                    Delimiter = ";",
                    MissingFieldFound = null
                });

reader.GetRecords<MyClass>().ToList();

My problem is that I get the following error at runtime:

enter image description here

It seems to say it isn’t able to understand the 2021-05-06 date, but not because the format is not valid, instead the error shows that Text: '', while I’d expect Text: '2021-05-06'. I tried using the [Format("yyyy-MM-dd")] attribute like said here, but without success (maybe because it’s only for writing, not reading).

Pine Code
  • 2,466
  • 3
  • 18
  • 43
  • I suggest you take a closer look at your data. In my small tests, I am unable to reproduce what you describe. The posted data appears to work as expected. I was unable to get the error you describe unless the date was missing or invalid. Are you sure the data file doesn’t have an “empty or invalid” `DateTime` value in column “ D”? It appears that if the `DateTime` value is “empty” in the file, then you will get the exception. However you could make the `DateTime` property nullable like… `public DateTime? d { get; set; }` … then only invalid dates will throw an exception. – JohnG Nov 26 '21 at 17:28
  • I agree with @JohnG. The data, as given, works just fine for me. – David Specht Nov 26 '21 at 17:41
  • @JohnG your advice is correct: using `DateTime?` solved the issue. To be honest, I don't understand why it works, since there're no empty `DateTime` values in the TXT file. The error stated the text CsvHelper was trying to convert was `Text: ''`, not `Text: '[a string possibly representing a DateTime]'`. Anyway, if you post your comment as an answer, I'll mark it as accepted. – Pine Code Nov 29 '21 at 09:00

0 Answers0