使用filehelpers导入包含可选字段的多行记录

时间:2014-09-10 13:51:12

标签: c# filehelpers

我需要解析一个文件,其记录的格式如下:

mr
Sean r.
Farrow
4 The Crescent
Eastleake
Loughborough
Leicestershire
LE12 6QH
01509 59213
07525945447
sean.farrow@seanfarrow.co.uk

每个记录都以空行分隔以完成。这两个电话号码和电子邮件地址是可选的。

解析此类记录的最佳方法是什么?我可以编写自己的解析器,但我希望我不必这样做!

1 个答案:

答案 0 :(得分:0)

FileHelpers期望每条记录以新行结束,因此您必须在将输入传递给引擎之前对其进行预解析。虽然这很简单 - 例如:

var lines = File.ReadAllLines(pathToImportFile);
var sb = new StringBuilder();
var separator = ","; // use a comma as field delimiter
foreach (string line in lines)
{
    if (String.IsNullOrEmpty(line))
        sb.AppendLine(""); // convert empty lines into line feeds
    else
        sb.AppendFormat("\"{0}\"{1}", line, separator); // put quotes around the field to avoid problems with nested separators
}
var engine = new FileHelperEngine<MyClass>();
engine.ReadString(sb.ToString());

你的班级看起来像

[DelimitedRecord(",")]
class MyClass
{
    [FieldQuoted(QuoteMode.AlwaysQuoted)]
    public string Title;

    [FieldQuoted(QuoteMode.AlwaysQuoted)]
    public string FullName;

    [FieldQuoted(QuoteMode.AlwaysQuoted)]
    public string Address1;

    /// ... etc        
}