Search code examples
c#filehelpers

sample of parsing CSV w/ FileHelpers when I don't know column names


I'm trying to use FileHelper 3.1.5 to parse user provided CSV files. I don't know the column names at compile time. I need a way to read the columns dynamically, both the column data and, possibly also header info.

Is that do-able? All the examples are parsing into static classes.


Solution

  • Sure you can do it. Use the FileHelpers class builder to build the import spec at runtime. Something like:

    // create a FileHelpers class with a comma delimiter.
    DelimitedClassBuilder cb = new DelimitedClassBuilder("Person", ",");
    // add your fields based on whatever logic you like (e.g., maybe read the column names from the first row)
    cb.AddField("firstName", typeof(string));
    cb.AddField("lastName", typeof(string));
    cb.LastField.FieldNullValue = "default last name";
    
    // create your import engine from the class you created above.
    DelimitedFileEngine engine = new DelimitedFileEngine(cb.CreateRecordClass());
    DataTable dt = engine.ReadFileAsDT("data.csv");