Search code examples
c#.netvisual-studiocsvhelper

Csv Helper write empty string instead of default DateTime


Hi I am facing an issue while writing default DateTime column on CSV file using csvHelper What I am doing is

  using (var memoryStream = new MemoryStream())
            {
                using (var streamWriter = new StreamWriter(memoryStream))
                {
                    using (var csvWriter = new CsvWriter(streamWriter, CultureInfo.InvariantCulture))
                    {
                        if (!string.IsNullOrEmpty(header))
                        {
                            csvWriter.WriteField(header);
                            csvWriter.NextRecord();
                        }
                        csvWriter.Configuration.TypeConverterOptionsCache.GetOptions<DateTime>().Formats = new[] { "dd/MM/yyyy" };
                        csvWriter.Configuration.TypeConverterOptionsCache.GetOptions<DateTime?>().Formats = new[] { "" };
                        csvWriter.Configuration.RegisterClassMap<TMap>();
                        csvWriter.WriteRecords(records);
                        WriteGrandTotals(columnTotals, csvWriter);
                    }
                }

                return memoryStream.ToArray();
            }

the results enter image description here

I have default DateTime in Db I want this default DateTime to be a null or empty string in the CSV column instead of this misleading data


Solution

  • You don't need type conversion here. The behavior you need is already there:

    using System.Collections;
    using System.Globalization;
    using CsvHelper;
    using CsvHelper.Configuration.Attributes;
    
    var records = new List<TMap>
    {
        new TMap { Id = 1, Stamp = DateTime.Now, Filer = "X"},
        new TMap { Id = 2, Stamp = null, Filer = "X" },
        new TMap { Id = 3, Stamp = DateTime.Now, Filer = "X" },
    };
    
    using (var writer = new StreamWriter("file.csv"))
    {
        using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
        {
            csv.WriteRecords((IEnumerable)records);
        }
    }
    
    class TMap
    {
        public int Id { get; set; }
    
        [Format("dd/MM/yyyy")]
        public DateTime? Stamp { get; set; }
        
        public string Filer { get; set; }
    }
    

    Result:

    Id,Stamp,Filer
    1,06/06/2022,X
    2,,X
    3,06/06/2022,X