Home > Software engineering >  CsvHelper: How to set output date format globally
CsvHelper: How to set output date format globally

Time:11-03

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?

CodePudding user response:

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);
  • Related