Search code examples
csvquotesstreamwritercsvhelper

CsvHelper wrap all values with quotes


I am using CsvHelper I need to wrap all values with quotes. Is that possible?

Data = is a List

 using (StreamWriter textWriter = new StreamWriter(path))
 {
     textWriter.BaseStream.Write(p, 0, p.Length);
     // var dt = new DataTable();
     var csv = new CsvWriter(textWriter);
     csv.WriteRecords(Data);
     textWriter.Flush();
     textWriter.Close();
 }

Thanks


Solution

  • There is a config value called ShouldQuote where you can determine on a field level if it should be quoted.

    void Main()
    {
        var records = new List<Foo>
        {
            new Foo { Id = 1, Name = "one" },
            new Foo { Id = 2, Name = "two" },
        };
    
        using (var writer = new StringWriter())
        using (var csv = new CsvWriter(writer))
        {
            csv.Configuration.ShouldQuote = (field, context) => true;
            csv.WriteRecords(records);
    
            writer.ToString().Dump();
        }
    }
    
    public class Foo
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
    

    Output:

    "Id","Name"
    "1","one"
    "2","two"