Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When I try to escape a double quote in C# I get multiple instead of just one

Tags:

c#

csv

For the purposes of my program, I need to read in data from a CSV file, process it, and then create a new batch of CSV files based on the data I read in. I am using the CsvHelper library if that makes a difference.

The program works perfectly, except for one part. I need my output CSV files to have each field wrapped in double quotes. Normally I would just use the escape mechanism for c#, but I ran into a bizarre issue that I can't seem to work around. Whenever I try to escape a " mark, I end up getting more than just the one.

Desired output example:

date_start,date_end,current_year
"2017-08-01","2018-06-20","2017"
"2017-08-01","2018-06-20","2017"

Observed output:

date_start,date_end,current_year
"""2017-08-01""","""2018-06-20""","""2017"""
"""2017-08-01""","""2018-06-20""","""2017"""

It puts in a pair of double quotes when I am just looking for one. I've looked around online and tried several different approaches to try and get just the one double quote, but I can't seem to make it work. Here is the relevant code and the different methods I have tried:

HashSet<CustomDataWrapper> hs = new HashSet<CustomDataWrapper>();

foreach (CustomDataType record in records) {
string quote = "\"";
String method1 = (String)(record.date_start);
String method2 = quote + record.date_start + quote;
String method3 = "\"" + record.date_start + "\"";
String method4 = "\U0022" + record.date_start + "\U0022"

hs.Add(data);
}

csvWriter.WriteRecords(hs);

I am honestly not sure what's going on here, as I've tried adding the quote to just one side of the string and got this output:

date_start,date_end,current_year
"2017-08-01""","2018-06-20""","2017"""
"2017-08-01""","2018-06-20""","2017"""

Any help would be greatly appreciated. Thank you!

like image 607
andyrichterr Avatar asked Nov 17 '25 11:11

andyrichterr


1 Answers

Stop adding quotes to the fields. Try creating configuration object and set the 'QuoteAllFields' to true and pass this object to CSVWriter as below

var config = new CsvHelper.Configuration.CsvConfiguration();
config.QuoteAllFields = true;

using (var csvReader = new CsvHelper.CsvReader(streamReader, config))
{
}

Hope this works.

like image 139
Cinchoo Avatar answered Nov 20 '25 01:11

Cinchoo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!