Saving and Loading file definitions while using <generic> version of FileEngine

114 Views Asked by At

I've successfully use the SaveToXml and LoadFromXml methods on the ClassBuilder class to store and retrieve the file definitions while using the Standard version of the File Helper Engine.

However I'd really prefer to use the generic version of the File Helper Engine. In other words I'd like to instatiate the engine like so:

var eng = new DelimitedFileEngine<OutputClass>(params....);

OutputClass[] records = eng.ReadFile("Sample.csv");

So my results are strongly typed and not just an array of objects.

Does this save and load functionality exist for the generic file helper engine?

1

There are 1 best solutions below

2
shamp00 On

Sure, it works exactly as you'd expect.

[DelimitedRecord("|")]
public class OutputClass
{
    public string First { get; set; }
    public string Second { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        var eng = new DelimitedFileEngine<OutputClass>();

        // To read from a file use ReadFile()
        //OutputClass[] records = eng.ReadFile("Sample.csv");

        // Or to read from a string use ReadString()
        OutputClass[] records = eng.ReadString("First|Second");
        Debug.Assert(records.Length == 1);
        Debug.Assert(records[0].First == "First");
        Debug.Assert(records[0].Second == "Second");
        
        Console.WriteLine("All OK");
        Console.ReadKey();
    }
}

Edit: Based on your comment below, you want to map the results from your XML class to a concrete C# object. The easiest way is to use read into a DataTable and map the fields to the C# object.

var cb = new DelimitedClassBuilder(nameof(OutputClass), "|");
cb.AddField("First", typeof(string));
cb.AddField("Second", typeof(string));
var xmlString = cb.SaveToXmlString();

var outputClass = DelimitedClassBuilder.LoadFromXmlString(xmlString);
var eng = new FileHelperEngine(outputClass.CreateRecordClass());

OutputClass[] records = eng
    .ReadStringAsDT("First|Second")
        .Rows.OfType<DataRow>()
            .Select(x => new OutputClass() { 
                First = x.Field<string>("First"), 
                Second = x.Field<string>("Second") 
            })
        .ToArray();