CsvHelper Configuration.ShouldQuote-仅对DTO上为字符串的字段返回true

时间:2019-06-13 11:50:21

标签: c# nuget csvhelper

嗨,他有一个DTO对象,该对象具有许多具有不同类型的属性,例如stringintbool等。

我只想在string属性周围加上双引号。

Configuration.ShouldQuote中,field参数值已全部转换为string,因此无法得知DTO的原始类型是否为stringintbool

是否有一种方法可以从DTO中找到基础属性类型,以便仅对原本类型为true的字段从Configuration.ShouldQuote传回string? >

public class TestDTO
{
    public string Field1 { get; set; }
    public int Field2 { get; set; }
    public bool Field3 { get; set; }
}
    var rawData = new[]
    {
        new TestDTO { Field1 = "Field1", Field2 = 1, Field3 = true },
        new TestDTO { Field1 = "Field2", Field2 = 10, Field3 = false }
    };
    using (var writer = new StreamWriter("file.csv"))
    {
        using (var csv = new CsvWriter(writer))
        {
            csv.Configuration.ShouldQuote = (field, context) =>
            {
                return field is string; // doesn't work as all fields at this point are strings
            };

            csv.WriteRecords(rawData);
        }
    }

1 个答案:

答案 0 :(得分:0)

我找不到使用ShouldQuote的方法,但是使用自定义转换器可能是一个很好的解决方法。

public class QuoteStringConverter : StringConverter
{
    public override string ConvertToString(object value, IWriterRow row, MemberMapData memberMapData)
    {
        var innerQuotes = ((string)value).Replace(row.Configuration.QuoteString, row.Configuration.DoubleQuoteString);
        var quotedValue = row.Configuration.Quote + innerQuotes + row.Configuration.Quote;
        return base.ConvertToString(quotedValue, row, memberMapData);
    }
}

关闭引号并将您的转换器添加到TypeConverterCache

var rawData = new[]
{
    new TestDTO { Field1 = "Field1", Field2 = 1, Field3 = true },
    new TestDTO { Field1 = "Field2", Field2 = 10, Field3 = false }
};

using (var writer = new StreamWriter("file.csv"))
using (var csv = new CsvWriter(writer))
{
    csv.Configuration.ShouldQuote = (field, context) => false;
    csv.Configuration.TypeConverterCache.AddConverter<string>(new QuoteStringConverter());

    csv.WriteRecords(rawData);
}