CsvHelper 将所有值用引号引起来

CsvHelper wrap all values with quotes

我正在使用 CsvHelper,我需要用引号将所有值括起来。 这可能吗?

数据=是一个列表

 using (StreamWriter textWriter = new StreamWriter(path))
 {
     textWriter.BaseStream.Write(p, 0, p.Length);
     // var dt = new DataTable();
     var csv = new CsvWriter(textWriter);
     csv.WriteRecords(Data);
     textWriter.Flush();
     textWriter.Close();
 }

谢谢

只需要添加一个配置对象。像这样

CsvHelper.Configuration.CsvConfiguration config = new CsvHelper.Configuration.CsvConfiguration();
               config.QuoteAllFields = true;
                var csv = new CsvWriter(textWriter, config);

有一个名为 ShouldQuote 的配置值,您可以在其中确定字段级别是否应引用它。

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; }
}

输出:

"Id","Name"
"1","one"
"2","two"

从25.0.0版本至今,做法是:

var config = new CsvConfiguration(CultureInfo.InvariantCulture)
{
    ShouldQuote = args => true
};