Search code examples
csvhelper

CSVHelper writing fixed lenght field


I've been writing csv files since now composing strings, but looking for a more structured solution I came a across to csvhelper. It's clear to me how to read data and perform type conversion, but what about when writing a csv file to specify the field lenght? suppose I've a field that starts from 0 and takes 4 char lenght... how can I specify this? I've not found and attribute or so....

Thanks


Solution

  • You could use a custom type converter to specify a fixed width.

    void Main()
    {
        var records = new List<Foo>
        {
            new Foo { Id = 1, Name = "one" },
        };
    
        using (var writer = new StreamWriter("path\\to\\file.csv"))
        using (var csv = new CsvWriter(writer))
        {
            csv.Configuration.RegisterClassMap<FooMap>();
            csv.WriteRecords(records);
        }
    }
    
    public class Foo
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
    
    public sealed class FooMap : ClassMap<Foo>
    {
        public FooMap()
        {
            AutoMap();
            Map(m => m.Id).TypeConverter<FixedWidthOutput>();
        }
    }
    
    public class FixedWidthOutput : Int32Converter
    {
        public override string ConvertToString(object value, IWriterRow row, MemberMapData memberMapData)
        {
            return value.ToString().PadLeft(4, '0');
        }
    }