1

We are upgrading an old .NET app to .NET Core 6.0, and so we need to upgrade all dependencies as well, including CsvHelper.

Our old code globally sets the output date format for all date fields in CSV as follows:

using (var writer = new StreamWriter(writeStream))
{
    var items = type?.GetProperty("Data")?.GetValue(value, null) as IEnumerable;
    var csvWriter = new CsvWriter(writer);

    csvWriter.Configuration.TypeConverterCache.AddConverter<Date>(new DateConverter());
    var dateTimeOptions = new TypeConverterOptions
            {
                Formats = new [] { FormatConstants.DefaultDateTimeFormat }
            };
            
    csvWriter.Configuration.TypeConverterOptionsCache.AddOptions(typeof(DateTimeOffset), dateTimeOptions);
    csvWriter.Configuration.TypeConverterOptionsCache.AddOptions(typeof(DateTime), dateTimeOptions);
    csvWriter.WriteRecords(items);
}

This is not possible with the current version of CsvHelper, because TypeConverterCache and TypeConverterOptionsCache are no longer available.

Similarly, the answer proposed here no longer works, because TypeConverterOptionsFactory is also not available.

All of the information I have found online requires every date field on every class to be mapped individually. This would be tedious and wasteful, because we have many DTO's with date fields, and we want them all to be output in the same format.

Is there a way to specify the output for all date fields globally, as we did in the older version?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Jim Robson
  • 23
  • 5
  • Would you be able to create a DTO for the CSV exporter? You could then add `[DataType(DataType.Date)]` as an attribute for the property you want displayed as a date – averybusinesssolutions Nov 02 '22 at 20:08
  • @averybusinesssolutions If I understand you correctly, that solution is what I am trying to avoid. I don't want to map every date field on every DTO. – Jim Robson Nov 02 '22 at 20:17

1 Answers1

3

I believe you just need to make a couple of adjustments.

Add CultureInfo or CsvConfiguration to CsvWriter

var csvWriter = new CsvWriter(writer, CultureInfo.InvariantCulture);

And TypeConverterCache and TypeConverterOptionsCache are now on csvWriter.Context

csvWriter.Context.TypeConverterCache.AddConverter<Date>(new DateConverter());

csvWriter.Context.TypeConverterOptionsCache.AddOptions(typeof(DateTimeOffset), dateTimeOptions);
csvWriter.Context.TypeConverterOptionsCache.AddOptions(typeof(DateTime), dateTimeOptions);
David Specht
  • 7,784
  • 1
  • 22
  • 30