使用CsvWriter配置ShouldQuote写入CSV时未添加引号
解决CsvWriter自定义ShouldQuote不生效的问题
问题分析
你配置了自定义ShouldQuote函数,期望给字符串类型字段添加双引号但未生效,常见原因包括:
- 映射后的对象属性类型并非
string,导致args.FieldType == typeof(string)判断不成立 - 自定义函数逻辑未覆盖目标场景(比如空字符串被排除,但实际需要引号)
- 未调试确认函数是否进入返回
true的分支
解决方案
1. 修正自定义ShouldQuote逻辑
调整函数逻辑,确保所有字符串类型字段都被引号包裹(可根据需求调整空字符串的处理规则):
protected virtual bool ReportShouldQuote(ShouldQuoteArgs args) { // 对所有字符串类型字段添加引号,无论内容是否为空 return args.FieldType == typeof(string); }
2. 验证映射对象的属性类型
检查mapFunc返回的T类型对象,确认需要加引号的属性确实是string类型。如果属性是object等其他类型,args.FieldType会不匹配,导致逻辑失效。
3. 确保配置未被覆盖
不要在CsvConfiguration中设置UseQuotes = UseQuotes.Never,默认的UseQuotes.AsNeeded会尊重自定义ShouldQuote的返回值:
var config = new CsvConfiguration(System.Globalization.CultureInfo.InvariantCulture) { ShouldQuote = ReportShouldQuote, // 保留默认的UseQuotes.AsNeeded,无需额外设置 };
4. 调试确认函数执行
在ReportShouldQuote方法中添加调试输出,确认函数是否被调用以及参数值是否符合预期:
protected virtual bool ReportShouldQuote(ShouldQuoteArgs args) { Console.WriteLine($"字段内容:{args.Field},类型:{args.FieldType}"); return args.FieldType == typeof(string); }
完整修正代码示例
protected virtual bool ReportShouldQuote(ShouldQuoteArgs args) { return args.FieldType == typeof(string); } // 写入CSV的逻辑 var config = new CsvConfiguration(System.Globalization.CultureInfo.InvariantCulture) { ShouldQuote = ReportShouldQuote }; using (StreamWriter writer = new StreamWriter(outputFilePath)) using (CsvWriter csv = new CsvWriter(writer, config)) { csv.WriteHeader<T>(); csv.NextRecord(); TotalRows = 0; while (dataReader.Read()) { var mappedData = mapFunc(dataReader); csv.WriteRecord(mappedData); csv.NextRecord(); TotalRows++; } }
内容的提问来源于stack exchange,提问作者Brandon Joplin
相关产品推荐
相关产品推荐

