disassemble-number-5
disassemble-number-5

Reputation: 995

Writing quotes to specific CSV fields with CsvHelper

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.

Upvotes: 4

Views: 3690

Answers (2)

Lee Richardson
Lee Richardson

Reputation: 8847

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;

Upvotes: 3

Lauraducky
Lauraducky

Reputation: 672

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...

Upvotes: 3

Related Questions