I'm working with the great FileHelpers library (version 2.9.9). However I've been stuck for some hours now and I'm not able to work this issue out. I would like to load my file into an array of my CustomerClass object. I would like to change the order of the fields dynamically utilizing the DelimitedClassBuilder. I found an answer here on Stackoverflow which shows how to do it https://stackoverflow.com/a/8833322/767926. I'm not able to do it even following that answer. However it works fine if I just use the class directly with the FileHelperEngine instead of DelimitedClassBuilder. Could somebody please help me out here?
This is the object i would like to create an array of from the csv file:
[DelimitedRecord(";")]
public class CustomerClass
{
public string CustomerId;
public string FirstName;
public string LastName;
}
This is the code I'm using to create the array:
public void ReadFile()
{
DelimitedClassBuilder cb = new DelimitedClassBuilder("CustomerClass", ";");
cb.AddField("CustomerId", typeof(string));
cb.AddField("FirstName", typeof(string));
cb.AddField("LastName", typeof(string));
FileHelperEngine engine = new FileHelperEngine(cb.CreateRecordClass());
engine.ErrorMode = ErrorMode.IgnoreAndContinue;
string filename = @"C:\temp\customerfile.csv";
DataTable dt = engine.ReadFileAsDT(filename); // Works fine
object[] test = engine.ReadFile(filename) as object[]; // Works fine
CustomerClass[] customers = engine.ReadFile(filename) as CustomerClass[]; // Returns null (probably because the 'cast' is invalid, see line below)
customers = (CustomerClass[])engine.ReadFile(filename); // Throws InvalidCastException (Unable to cast object of type 'CustomerClass[]' to type 'MyNamespace.CustomerClass[]'.)
}
This is the file contents:
CustomerId;FirstName;LastName
1;James;Brown
2;Robert;Miller
3;David;Green