The problem is you are trying to fight CsvHelper's quoting. According to the RFC 4180 specifications.
- Fields containing line breaks (CRLF), double quotes, and commas
should be enclosed in double-quotes. For example:
"aaa","b CRLF
bb","ccc" CRLF
zzz,yyy,xxx
- If double-quotes are used to enclose fields, then a double-quote
appearing inside a field must be escaped by preceding it with
another double quote. For example:
"aaa","b""bb","ccc"
So when you add double quotes to the field, CsvHelper recognizes that the whole field needs to be enclosed in double quotes and the added quotes need to be escaped with another double quote. That is why you end up with 3 double quotes.
CsvHelper has a configuration function where you can tell it when it should quote a field. @JoshClose already has an answer here for wrapping all fields in double quotes. I'll update it for the current version of CsvHelper.
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, CultureInfo.InvariantCulture))
{
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; }
}
If you still wanted to add the double quotes yourself, you could turn off CsvHelper's double quoting.
csv.Configuration.ShouldQuote = (field, context) => false;
Breaking change for Version 20.0.0 and later
Changed CsvConfiguration to a read only record to eliminate threading issues.
You would need to create CsvConfiguration
, set ShouldQuote
on initialization and then pass it to the CsvWriter
.
void Main()
{
var records = new List<Foo>
{
new Foo { Id = 1, Name = "one" },
new Foo { Id = 2, Name = "two" },
};
var config = new CsvConfiguration(CultureInfo.InvariantCulture)
{
ShouldQuote = (field, context) => true
};
using (var writer = new StringWriter())
using (var csv = new CsvWriter(writer, config))
{
csv.WriteRecords(records);
writer.ToString().Dump();
}
}
public class Foo
{
public int Id { get; set; }
public string Name { get; set; }
}