CsvHelper - 如何配置报价设置?
当规格数据有引号(“Jake”)时,我收到下面的错误消息。
“CsvHelper.BadDataException:您可以通过将 BadDataFound 设置为 null 来忽略错误数据。”
当我删除日志的引用(杰克)时它将起作用。
那么问题来了,如何配置报价的设置呢?
请注意,日志中有一个不带引号的列。
CSV
Id,Name,Type
1, "Jake",User
映射
public LogProfile()
{
Map(m => m.Id).Name("Id");
Map(m => m.Name).Name("Name");
Map(m => m.Type).Name("Type");
}
转换
const string headerPrefix = "Id,";
var path = @"D:\test.csv";
var readConfiguration = new CsvConfiguration(CultureInfo.InvariantCulture)
{
ShouldQuote = x => x.Field.Contains("\"")
};
var input = new List<LogRecord>();
using (var reader = new StreamReader(path))
using (var csv = new CsvReader(reader, readConfiguration))
{
csv.Context.RegisterClassMap<LogProfile>();
var isHeader = true;
while (csv.Read())
{
if (isHeader)
{
if(csv.Parser.RawRecord.Contains(headerPrefix))
{
csv.ReadHeader();
isHeader = false;
}
continue;
}
input.Add(csv.GetRecord<LogRecord>());
}
}
Logger.LogInformation($"Done {path}");
When the spec data has quote ("Jake"), I got an error message below.
"CsvHelper.BadDataException: You can ignore bad data by setting BadDataFound to null."
It will work when I remove log's quote (Jake).
So the question is how to config the setting about quote?
Notice the log has a col with no quote.
CSV
Id,Name,Type
1, "Jake",User
MAP
public LogProfile()
{
Map(m => m.Id).Name("Id");
Map(m => m.Name).Name("Name");
Map(m => m.Type).Name("Type");
}
Convert
const string headerPrefix = "Id,";
var path = @"D:\test.csv";
var readConfiguration = new CsvConfiguration(CultureInfo.InvariantCulture)
{
ShouldQuote = x => x.Field.Contains("\"")
};
var input = new List<LogRecord>();
using (var reader = new StreamReader(path))
using (var csv = new CsvReader(reader, readConfiguration))
{
csv.Context.RegisterClassMap<LogProfile>();
var isHeader = true;
while (csv.Read())
{
if (isHeader)
{
if(csv.Parser.RawRecord.Contains(headerPrefix))
{
csv.ReadHeader();
isHeader = false;
}
continue;
}
input.Add(csv.GetRecord<LogRecord>());
}
}
Logger.LogInformation(quot;Done {path}");
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
尝试使用
TrimOptions.Trim
的Configuration
设置。Try it with the
Configuration
setting ofTrimOptions.Trim
.