Tim Kathete Stadler
Tim Kathete Stadler

Reputation: 1069

StringBuilder export csv with quotation marks at the beginning

I want to write several csv lines into a csv file with StringBuilder. I enclose every field with quoation marks. If I export the file as a .txt I have excactly what I want ("Artist","Album","Track"). If I export as .csv the first field is not enclosed with quoation marks (Artist,"Album","Track"). Some test code that reproduces the issue:

static void Main(string[] args)
{
  StringBuilder csv = new StringBuilder();

  string artist = EncloseComma("Artist");
  string album = EncloseComma("Album");
  string track = EncloseComma("Track");

  string newLine = string.Format("{0},{1},{2}", artist, album, track);
  csv.AppendLine(newLine);
  File.WriteAllText("test.csv", csv.ToString());
}

private static string EncloseComma(string str)
{
  return "\"" + str + "\"";
}

Upvotes: 1

Views: 1749

Answers (2)

tRuEsAtM
tRuEsAtM

Reputation: 3668

This code worked for me:

    private static string AddDoubleQuotes(string str)
    {
        str = $"\"" + "\"" + "\"" + str + "\"" + "\"" + "\"";
        return str;
    }

Just add two more escape characters like \" in total 3.

Upvotes: 1

Danny_ds
Danny_ds

Reputation: 11406

While the quotes will be visible in Notepad for example, it is quite normal they don't appear in Excel or when read with another csv parser.

The quotes in a csv file are only there to enclose fields that could have a delimiter inside them (they don't even mean the field should be treated as a string, quotes could as well be around numbers containing a separator).

To have the quotes still visible after parsing, they have to be escaped with another quote, and then surrounded with quotes to have a quoted field, like this:

"""Artist""","""Album""","""Track"""

For the same reason, when generating a csv file from code, every field should be checked for delimiters and quotes and those quotes then have to be escaped with another quote.

Upvotes: 1

Related Questions