Search code examples
c#csvcsvhelper

Why do I have quotes in CSV File?


With this code I want to write header:

const string Header = "Name;Date";

using (var writer = new StreamWriter(path))
{
   var csvWriter = new CsvWriter(writer);

   csvWriter.Configuration.Delimiter = ";";

   csvWriter.WriteField(Header);
   csvWriter.NextRecord();
   ...

Open file after it:

"Name;Date"

What I want:

Name;Date

Solution

  • Quotes in CSV help to disambiguate when you want to include the delimiter in text that is in an individual field. For example, if I am using regular CSV (with commas as the delimiter), one of the fields might be the address. But if my address is 12 Some Street, Amazing Town, then I can't store that "as is" - the comma will make any parser think that the address is 12 Some Street, and the next field is Amazing Town. So if the value to be stored contains the delimiter, or a newline (for similar reasons, but: next record), quotes are used to tell it what you mean.

    In your case, your delimiter is ; and the value contains ; - so yes, it needs quotes. I suspect you actually meant to write two headers, one Name, one Date. For example:

    csvWriter.WriteField("Name");
    csvWriter.WriteField("Date");
    csvWriter.NextRecord();