【问题标题】:FileHelpers nested quotes and commas - parsing errorFileHelpers 嵌套引号和逗号 - 解析错误
【发布时间】:2014-02-03 18:40:11
【问题描述】:

我正在尝试使用出色的 FileHelpers 库从地狱中解析 CSV 文件。

无法处理表格的一行:

"TOYS R"" US"," INC.""",fld2,fld3,"<numberThousands>","<numberThousands>","<numberThousands>",fld7,

FileHelper 非常擅长处理“千”格式的数字字段(使用自定义格式化程序),即使用引号、尾随逗号等包裹,但它会导致第一个字段出现问题。

"TOYS R"" US"," INC.""",fld2,...

此字段包括嵌套引号和嵌套逗号。 FileHelper 不知道如何处理,并将其拆分为两个单独的字段,这随后会引发异常。

有没有推荐的方法来处理这个问题?

【问题讨论】:

    标签: c# parsing csv filehelpers


    【解决方案1】:

    首先,您需要将所有字段设为可选引用。

    [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(@"""", "'");
    

    【讨论】:

    • 我想过这一点,但不幸的是 RecordLine 不能公开设置。我目前正在手动解析该行(在 BeforeReadRecord 中)并将 SkipThisRecord 设置为 true。哈克,但它有效。
    • 当然RecordLine 是可设置的。请参阅注释at the bottom of the page here。您使用的是哪个版本?你确定你没有尝试设置Record 吗?
    • 没有 { set; } 属性访问者:filehelpers.sourceforge.net/…
    • 该属性可在FileHelpers 2.9.9 中设置。 2.0.0.0 版本是 2007 年的。您可以:升级;修改源;或使用您现有的 hack。
    猜你喜欢
    • 1970-01-01
    • 2016-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-17
    • 2012-10-10
    相关资源
    最近更新 更多