Search code examples
c#csvhelper

Control header field names with CsvHelper


When writing CSV file using CsvHelper 6.1.0, the documentation only once mentions controlling the header name on write:

"When writing, only the first name is used."

My code conforms with the example given:

Map(m => m.ReportingGroup).Name("Reporting Group");
Map(m => m.Merchant);
Map(m => m.ActivityDate).Name("Activity Date");
Map(m => m.SettlementDate).Name("Settlement Date");

The spaces are not written during the write operation!

ReportingGroup,Merchant,ActivityDate,SettlementDate

My Read() and Write(), if needed:

public static IEnumerable<TR> Read<TR, TMap>(string filename)
    where TMap : ClassMap
{
    List<TR> records;
    using (var sr = new StreamReader(filename))
    {
        var csv = new CsvReader(sr);
        csv.Configuration.RegisterClassMap<TMap>();
        records = csv.GetRecords<TR>().ToList();
    }
    return records;
}

public static void Write<T>(IEnumerable<T> records, string filename, Logger logger)
{
    var enumerable = records as IList<T> ?? records.ToList();
    logger?.Debug($"Writing {enumerable.Count} records to file: {filename}");
    using (var fcreate = File.Open(filename, FileMode.Create))
    using (var writer = new StreamWriter(fcreate))
    {
        var csv = new CsvWriter(writer);
        csv.WriteRecords(enumerable);
    }
    logger?.Debug("Writing complete.");
}

Solution

  • You need to register your class map when writing. It looks like you have it on reading, but it's missing on writing.