Search code examples
c#csvhelper

How to get the field name to check if field should include quotes or not?


I need to add quotes to some fields. The field type should not considered because some strings should have quotes and others not.

So I added the following configuration:

var config = new CsvConfiguration(CultureInfo.InvariantCulture) {
    ShouldQuote = args =>
    {
        var b = quoted.Contains(args.Field);
        return b;
    }
};

The quoted variable is a list of field names that need quotes.

But args.Field is not the field name but the field value. Is there a way to check what the field name is at this stage or maybe there is another way to achieve this?


Solution

  • You can use args.Row.HeaderRecord along with args.Row.Index to determine the header name of the field. If you also want the actual header name quoted, you will have to check args.field since the HeaderRecord will not have been populated at that point.

    void Main()
    {
        var quoted = new List<string> { "Id" };
        var config = new CsvConfiguration(CultureInfo.InvariantCulture)
        {
            ShouldQuote = args =>
            {
                if (args.Row.HeaderRecord != null)
                {
                    return quoted.Contains(args.Row.HeaderRecord[args.Row.Index]);
                }
                
                if (args.Row.Row == 1)
                {
                    return quoted.Contains(args.Field);
                }
                
                return false;
            }
        };
    
        var records = new List<Foo>{
            new Foo { Id = 1, Name = "Name1" },
            new Foo { Id = 2, Name = "Name2" }
        };
    
        using (var csv = new CsvWriter(Console.Out, config))
        {
            csv.WriteRecords(records);
        }
    }
    
    // Define other methods and classes here
    public class Foo
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }