FileHelpers引用的字段包含单引号?

时间:2017-05-16 10:26:55

标签: csv filehelpers

如何阅读FileHelpers引用的字段包含单引号?

以下是我的csv记录

"1","7" Screen","Mobile"

型号:

[DelimitedRecord(",")]

public class LineModel 
{

 [FieldQuoted('"', QuoteMode.OptionalForBoth)]

 public string Id;

 [FieldQuoted('"', QuoteMode.OptionalForBoth)]

 public string Details;

 [FieldQuoted('"', QuoteMode.OptionalForBoth)]

 public string Device;

}

获取上述记录的错误: - 引用字段详细信息,但引用的字符:"不在分隔符之前(您可以使用[FieldTrim]来避免此错误)

1 个答案:

答案 0 :(得分:0)

如果输入文件中的引号不明确,则

QuoteMode无法正常工作。相反,您可以删除[FieldQuoted]属性并处理自定义转换器中的引号。

[DelimitedRecord(",")]
public class LineModel
{
    [FieldConverter(typeof(MyQuotedFieldConverter))]
    public string Id;

    [FieldConverter(typeof(MyQuotedFieldConverter))]
    public string Details;

    [FieldConverter(typeof(MyQuotedFieldConverter))]
    public string Device;
}

public class MyQuotedFieldConverter : ConverterBase
{
    public override object StringToField(string from)
    {
        // If the field starts and ends with a double quote
        if (from.StartsWith("\"") && from.EndsWith("\""))
        {
            // Remove the first and last character
            return from.Substring(1, from.Length - 1);
        }
        return from;
    }
}

当然,如果你有","那么你会遇到麻烦。在你的领域内。

"1","7, Screen","Mobile"

在这种情况下,您必须通过实现INotifyRead接口来预解析记录行以清理输入。类似的东西:

[DelimitedRecord(",")]
public class LineModel : INotifyRead
{
    //... fields as before

    public void BeforeRead(BeforeReadEventArgs e)
    {
        if (e.RecordLine.Count(x => x == ',') > 3)
        {
            e.RecordLine = DetectAndReplaceEmbeddedDelimiters(e.RecordLine);
        }
    }

    public void AfterRead(AfterReadEventArgs e)
    {                
    }
}

另一种考虑相反的方法:使用自定义转换器为每个字段添加引号并删除/替换嵌入的引号。然后使用QuoteMode.AlwaysQuoted