0

I am trying to write a List of type string to a csv file and I want any string values to be enclosed in double quotes when written to the file. This certainly seems like a very basic problem, but I am not sure why I am struggling with this. I really must be drunk right now. Appreciate any help on this.

Here is a dumbed down version of what I am trying :

using System.Text;

string myString1 = string.Empty;
string myString2 = string.Empty;
List<string> myList = new List<string>();
StringBuilder sb = new StringBuilder();

//Assign value to myString1 variable, Note: object.Text returns a string value
myString1 = object.Text ;
myString2 = "Hello World";

myList.Add(myString1);
myList.Add(myString2);
sb.AppendLine(string.Join(",", myList));

File.WriteAllText(@"C:\Test.csv", sb.ToString());

Note : object.Text may also contain one or more double quote within the text in some instances. E.g. Table 1/4"" x 1/4""

Expected output : if myString1 was set as Hello World then

Output: "Hello World", "Hello World"

Maverick
  • 1,396
  • 5
  • 22
  • 42

1 Answers1

2

I'd recommend checking out a package like CsvHelper for reading and writing CSV files, but if you want to do it in code yourself, this works (including the correct comment that double quotes must be escaped with another double quote when the cell is quoted):

var myList = new List<string>()
{
   "John, Jr", "John \"Johnnie\", Jr"   
};

foreach (var quotedCell in myList.Select(c => $"\"{c.Replace("\"", "\"\"")}\""))
    Console.WriteLine(quotedCell);

Output:

"John, Jr"

"John ""Johnnie"", Jr"

Or if you want your original list in a new list:

var newList = myList
    .Select(c => $"\"{c.Replace("\"", "\"\"")}\""))
    .ToList();

Or if you want it all in a file with minimal fuss:

File.WriteAllText(@"C:\Test.csv", 
    string.Join(Environment.NewLine, 
        myList.Select(c => $"\"{c.Replace("\"", "\"\"")}\"")));

It looks a little awkward because we have to quote double quotes in C#. The idea is to put a double quote at the beginning and end of each string in your list and replace any occurrence of double quote in the original string with two double quotes per the CSV RFC.

With this approach, you'll quote every cell in the output, which will result in slightly larger file sizes than if you only quote when you need to (when there's a comma or newline-type character in the string).

Eric J.
  • 147,927
  • 63
  • 340
  • 553