0

I'm in the process of needing to parse a file who's records are of the following format:

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

Each record is delimited by a blank line to finish. The two phone numbers and email address are optional.

What is the best way of parsing this sort of record? I could write my own parser, but am hoping I don't have to!

NotMe
  • 87,343
  • 27
  • 171
  • 245
Sean Farrow
  • 69
  • 1
  • 3

1 Answers1

1

FileHelpers expects each record to end with a new line, so you'd have to pre-parse the input before passing it the engine. That's straightforward to do though - something like:

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());

and your class would look something like

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

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

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

    /// ... etc        
}
shamp00
  • 11,106
  • 4
  • 38
  • 81