Search code examples
c#csvhelper

C# CSVhelper unable to write using a custom mapping


I have recently moved from CSVHelper version 16.0.0 to 27.2.1. It seems to me for the CSV writer the mappings are lost as they are contained in the CSVContext now, instead of the CSVConfiguration.

I would like to use a custom Mapping to write to the CSV and not an autogenerated Mapping, is there a way to do this now?

using (StreamWriter _stream = new StreamWriter(_fileLocation))
{
  using (CsvWriter _csvWriter = new CsvWriter(_stream, CsvContext.Configuration))
  {
      _csvWriter.WriteRecords(items);
      _csvWriter.Flush();
  }
}

I added the code as context, as you can see the CSVWriter only accepts the Configuration, which no longer contains the mapping, so when I check the CSVWriter's context, there is no mapping. If I check the CSVContextitself, I do see a mapping, the custom one I made earlier.

example:

public class Foo
{
    public Guid id {get;set;}   
    public string name {get;set;}
    public DateTime created {get;set;}
}

So let's say I have the class Foo as above and I create a custom class mapping using the factory so:

private static ClassMap CreateMap()
{
    Factory _factory = new Factory();
            
    IHasMap<Foo> _mapper = _factory.CreateClassMapBuilder<Foo>();       
    
    _mapper.Map(x => x.id);
    _mapper.Map(x => x.name);       
    
    return _mapper.Build();
}   

And then i register the Mapping as such:

_context.RegisterClassMap(CreateMap());

I will end up with the result:

Id,name,Date
d2e0b6d5-356c-4c34-9437-92942ee9232c,SomeName,2020-01-01

but the result I want is:

Id,name
d2e0b6d5-356c-4c34-9437-92942ee9232c,SomeName

I want to make one thing clear, this was working under version 16.0.0.0


Solution

  • RegisterClassMap moved from the Configuration to the Context. You have to register it on the CsvWriter.Context.

    public static void Main(string[] args)
    {    
        var config = new CsvConfiguration(CultureInfo.InvariantCulture)
        {
            // Configuration settings
        };
        
        using (CsvWriter _csvWriter = new CsvWriter(Console.Out, config))
        {
            var fooRecords = new List<Foo> { new Foo { id = new Guid("d2e0b6d5-356c-4c34-9437-92942ee9232c"), name = "SomeName", created = new DateTime(2020,1,1)} };
    
            _csvWriter.Context.RegisterClassMap(CreateMap());
    
            _csvWriter.WriteRecords(fooRecords);
    
            _csvWriter.Flush();
            
            Console.Read();
        }            
    }
    
    public class Foo
    {
        public Guid id {get;set;}   
        public string name {get;set;}
        public DateTime created { get; set; }
    }
    
    private static ClassMap CreateMap()
    {
        Factory _factory = new Factory();
    
        IHasMap<Foo> _mapper = _factory.CreateClassMapBuilder<Foo>();
    
        _mapper.Map(x => x.id);
        _mapper.Map(x => x.name);
    
        return _mapper.Build();
    }