我正在尝试使用出色的 FileHelpers 库解析来自 hell 的 CSV 文件。
它无法处理表单的一行:
"TOYS R"" US"," INC.""",fld2,fld3,"<numberThousands>","<numberThousands>","<numberThousands>",fld7,
FileHelper 非常擅长处理“千”格式的数字字段(使用自定义格式化程序),即使用引号、尾随逗号等包裹,但它会导致第一个字段出现问题。
"TOYS R"" US"," INC.""",fld2,...
此字段包括嵌套引号和嵌套逗号。 FileHelper 不知道如何处理此问题并将其拆分为两个单独的字段,这随后会导致抛出异常。
有没有推荐的方法来处理这个问题?
最佳答案
首先,您需要对所有字段进行可选引用。
[DelimitedRecord(",")]
public class contactTemplate
{
[FieldQuoted('"', QuoteMode.OptionalForBoth)]
public string CompanyName;
[FieldQuoted('"', QuoteMode.OptionalForBoth)]
public string fld2;
// etc...
}
然后你需要在
BeforeReadRecord
中用其他东西(例如,单引号)替换转义的分隔符事件。var engine = new FileHelperEngine<MyFileHelpersSpec>();
engine.BeforeReadRecord += (sender, args) =>
args.RecordLine = args.RecordLine.Replace(@"""", "'");
关于c# - FileHelpers 嵌套引号和逗号 - 解析错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21134981/