Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format("T") attribute doesn't work if ClassMap was used

Tags:

c#

csv

csvhelper

I used to have the format attribute defined in the class like this

  [Format("T")]
  public required TimeOnly ArrivalTime { get; set; }

This exports the field in the hh:mm:ss format.

But when I change to use to the ClassMap, i.e., csv.Context.RegisterClassMap(). It doesn't seem to pick up the specified format. It exports the field in the hh:mm format.

Below is a sample code. Uncomment the RegisterClassMap line to see the effect.

using System.Globalization;
using CsvHelper;
using CsvHelper.Configuration;
using CsvHelper.Configuration.Attributes;

namespace csvhelperDateTime
{
    internal class Program
    {
        static void Main(string[] args)
        {
            using var writer = new StreamWriter("./output.csv");
            using var csv = new CsvWriter(writer, CultureInfo.CurrentCulture);
            var records = new List<MyClass>
                {
                    new() { ArrivalTime = TimeOnly.FromDateTime(DateTime.Now) },
                };

            // Uncomment the line below to use register MyClassMap
            // csv.Context.RegisterClassMap<MyClassMap>();

            csv.WriteRecords(records);
        }
    }

    public class MyClass
    {
        [Format("T")]
        public required TimeOnly ArrivalTime { get; set; }
    }


    public sealed class MyClassMap : ClassMap<MyClass>
    {
        public MyClassMap()
        {
            Map(m => m.ArrivalTime);
        }
    }
}
like image 997
user27465760 Avatar asked Apr 23 '26 21:04

user27465760


1 Answers

If you want the MyClassMap to completely configure the CSV, you can explicitly specify the format in the MyClassMap constructor:

Map(m => m.ArrivalTime).TypeConverterOption.Format("T");

Otherwise, to use the attributes:

ApplyAttributes(Map(m => m.ArrivalTime));

How to use a combination of the two:

ApplyAttributes(Map(m => m.ArrivalTime));
Map(m => m.ArrivalTime).TypeConverterOption.CultureInfo(
    System.Globalization.CultureInfo.GetCultureInfo("ar-SA"));

This also works to pick up everything as was before, after which you can make only specific edits you need:

AutoMap(CultureInfo.InvariantCulture);
Map(m => m.ArrivalTime).TypeConverterOption.Format("HH_mm_ss");
like image 181
relatively_random Avatar answered Apr 26 '26 10:04

relatively_random



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!