Search code examples
c#csvhelper

CSV Helpers quoting everything


I am wanting to quote just strings in csvhelper however this is quoting every field including the header record. I obv do not want the header record to be included in the quoting is their a way to skip it and also only quote strings.

 public static void writeCsvFile(List<SOPOrder> sopOrders, string filename)
 {
        using (var writer = new StreamWriter(filename))
        using (var csv = new CsvWriter(writer))
        {
            csv.Configuration.TrimOptions=CsvHelper.Configuration.TrimOptions.Trim;

            csv.Configuration.ShouldQuote = (field, context) => true;
            csv.WriteRecords(sopOrders);
        }
 }

Solution

  • There isn't a good way in CsvHelper to only quote string fields. You can hack it though by not quoting any fields and then using a custom StringConverter to do the quoting of the string fields.

    using (var csv = new CsvWriter(Console.Out))
    {
        var records = new List<Foo>
        {
            new Foo { Id = 1, Name = "First, Record" },
            new Foo { Id = 2, Name = "Second \"Record" },
            new Foo { Id = 3, Name = "" },
            new Foo { Id = 4 }
        };
    
        csv.Configuration.ShouldQuote = (field, context) => false;
        csv.Configuration.TypeConverterCache.AddConverter<string>(new QuoteStringConverter());
    
        csv.WriteRecords(records);
    }
    
    public class Foo
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
    
    public class QuoteStringConverter : StringConverter
    {
        public override string ConvertToString(object value, IWriterRow row, MemberMapData memberMapData)
        {
            if (value == null)
                return "\"\"";
    
            return "\"" + ((string)value).Replace("\"", "\"\"") + "\"";
        }
    }