3
votes

When writing a CSV file there is a need to quote only specific columns. Using CsvHelper 6.1.0, Is there some way to individually configure fields, particually whether they are quoted?

Field1,Field2,Field3,Field4,Field5,Field6 "Quoted","Quoted",NotQuoted,NotQuoted,NotQuoted,"Quoted" "Quoted","Quoted",NotQuoted,NotQuoted,NotQuoted,"Quoted"

So far I've only found, in the configuration object, QuoteAllFields and QuoteNoFields.

2
Why are you using CsvHelper to write a very simple csv file? Better to write using StreamWriter class. You can create a csv line using string outputline = string.Join("," new string[] { colA, colB, colC, colD}); writer.Writeline(outputline); - jdweng
@jdweng quite a bit more work is being done that isn't necessary to show. Just need to learn if and how to configure quotations on a per-field basis. - disassemble-number-5
Don't know if you can do with CSVHelper. Very simple with Net Library methods. - jdweng

2 Answers

2
votes

You can do this using Class Mapping.

You can start out by automapping the class, then edit the fields you want to appear in quotes. Something like this:

public sealed class MyClassMap : ClassMap<MyClass> {
    public MyClassMap() {
        AutoMap();
        Map(m => m.Field1).ConvertUsing(m => $"\"{m.Field1}\"");
        Map(m => m.Field2).ConvertUsing(m => $"\"{m.Field2}\"");
        Map(m => m.Field6).ConvertUsing(m => $"\"{m.Field6}\"");
    }
}

Then you apply it when you're writing the file like so:

CsvWriter myWriter = new CsvWriter(stream);
myWriter.Configuration.RegisterClassMap<MyClassMap>();

I'm not entirely sure if this is the "right" way to do this, however it certainly seems the simplest. You could implement a TypeConverter that puts in the quotes, but that seems like too much work for something so simple...

2
votes

I know OP asked about 6.1.0, but in case it helps others, there is a better solution as of version 12:

var indexesToQuote = new[] { 0, 2 };
csv.Configuration.ShouldQuote = (field, context) => 
    indexesToQuote.Contains(context.Record.Count) && 
    context.HasHeaderBeenWritten;