22

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

dcg
  • 4,187
  • 1
  • 18
  • 32
Ovi
  • 2,459
  • 9
  • 50
  • 72

3 Answers3

30

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"
Josh Close
  • 22,935
  • 13
  • 92
  • 140
12

From version 25.0.0 up to the date, the way of doing it is:

var config = new CsvConfiguration(CultureInfo.InvariantCulture)
{
    ShouldQuote = args => true
};
Nahue Gonzalez
  • 273
  • 4
  • 10
2

Just need to add a configuration object. like this

CsvHelper.Configuration.CsvConfiguration config = new CsvHelper.Configuration.CsvConfiguration();
               config.QuoteAllFields = true;
                var csv = new CsvWriter(textWriter, config);
Ovi
  • 2,459
  • 9
  • 50
  • 72