Home > Software engineering >  How to write unescaped quoted values
How to write unescaped quoted values

Time:08-06

Does CsvHelper not support quoted unescaped output or is there something wrong with my writer configuration?

Input:

Jake|"B" Street

CsvHelper reader configuration:

var readerConfig = new CsvConfiguration(CultureInfo.InvariantCulture)
{
    Delimiter = "|",
    TrimOptions = TrimOptions.Trim,     
    IgnoreBlankLines = true,
    Mode = CsvMode.NoEscape
};

After record is read into memory, the value with double quotes is unescaped as expected: "B" Street

However, when I write records to CSV file if ShouldQuote = args => true is used without CsvMode.NoEscape double quotes are escaped and if I add CsvMode.NoEscape the output is not quoted at all.

writerConfiguration = new CsvConfiguration(CultureInfo.InvariantCulture)
{
    ShouldQuote = args => true,
    Mode = CsvMode.NoEscape
};

Output with CsvMode.NoEscape: "B" Street // Output not quoted and not escaped.

Output without CsvMode.NoEscape: """B"" Street" // Double quotes escaped.

Any ideas on how to write unescaped quoted values with CsvHelper?

CodePudding user response:

This feels a little hacky, but I was able to do what I think you are trying to do with CsvMode.NoEscape and a custom string converter to add the outer quotes. Another option would be to use Convert in a ClassMap to add the outer quotes on a column by column basis.

void Main()
{
    var records = new List<Foo>
    {
        new Foo { Id = 1, Name = "\"B\" Street" },
    };
    
    var config = new CsvConfiguration(CultureInfo.InvariantCulture)
    {
        Mode = CsvMode.NoEscape
    };

    using (var csv = new CsvWriter(Console.Out, config))
    {
        csv.Context.TypeConverterCache.AddConverter<string>(new OuterQuoteConverter());
        csv.WriteRecords(records);
    }
}

public class OuterQuoteConverter : StringConverter
{
    public override string ConvertToString(object value, IWriterRow row, MemberMapData memberMapData)
    {
        var quoted = "\""   (string)value   "\"";
        return base.ConvertToString(quoted, row, memberMapData);
    }
}

public class Foo
{
    public int Id { get; set; }
    public string Name { get; set; }
}
  • Related