CsvHelper wrap all values with quotes

后端 未结 2 1692
青春惊慌失措
青春惊慌失措 2021-01-11 15:31

I am using CsvHelper I need to wrap all values with quotes. Is that possible?

Data = is a List

 using (StreamWriter textWriter = new StreamWriter(pat         


        
相关标签:
2条回答
  • 2021-01-11 15:50

    Just need to add a configuration object. like this

    CsvHelper.Configuration.CsvConfiguration config = new CsvHelper.Configuration.CsvConfiguration();
                   config.QuoteAllFields = true;
                    var csv = new CsvWriter(textWriter, config);
    
    0 讨论(0)
  • 2021-01-11 16:07

    There is a config value called ShouldQuote where you can determine on a field level if it should be quoted.

    void Main()
    {
        var records = new List<Foo>
        {
            new Foo { Id = 1, Name = "one" },
            new Foo { Id = 2, Name = "two" },
        };
    
        using (var writer = new StringWriter())
        using (var csv = new CsvWriter(writer))
        {
            csv.Configuration.ShouldQuote = (field, context) => true;
            csv.WriteRecords(records);
    
            writer.ToString().Dump();
        }
    }
    
    public class Foo
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
    

    Output:

    "Id","Name"
    "1","one"
    "2","two"
    
    0 讨论(0)
提交回复
热议问题