Search code examples
c#.netfilehelpers

How to cast to a dynamic class?


I am trying use filehelpersclass builder but I am kinda confused on what to do with it.

       var cb = new DelimitedClassBuilder("temp", ",") { IgnoreFirstLines = 0, IgnoreEmptyLines = true, Delimiter = ","  };
        var sr = new StreamReader(stream);
        var headerArray = sr.ReadLine().Split(',');
        foreach (var header in headerArray)
        {
            var fieldName = header.Replace("\"", "").Replace(" ", "");
            cb.AddField(fieldName, typeof(string));
        }

        var engine = new FileHelperEngine(cb.CreateRecordClass());
        var result = engine.ReadStream(sr);

The DelimitedClassBuilder takes in as it's first parameter a "className' and then "delimiter"

    //
    // Summary:
    //     Creates a new DelimitedClassBuilder.
    //
    // Parameters:
    //   className:
    //     The valid class name.
    //
    //   delimiter:
    //     The delimiter for that class.
    public DelimitedClassBuilder(string className, string delimiter);

I then go through the first row of the stream what contains the header what I will later on use as the fieldNames for this "class".

The last line reads all the rest of the information and returns it as an object array[]. I see inside it they are of class "temp".

Yet I don't know how actually cast it to the class "temp". Right now I don't really know how to get at the data. I know I can't just do something like

result[0].SomeFieldName as the fieldName could change from run to run. So this also makes me wonder why it makes a class in the first place if I going to have to do something like get it by index or something.

As you can see right now I am very confused.


Solution

  • The easiest way is demonstrated in the examples.

    You use

    DataTable dt = engine.ReadStreamAsDT(sr);
    

    and then access the results with something like:

    foreach (DataRow row in dt.Rows) // Loop over the rows.
    {
        Console.WriteLine("--- Row ---"); // Print separator.
        foreach (var item in row.ItemArray) // Loop over the columns.
        {
            Console.Write("Item: "); // Print label.
            Console.WriteLine(item); 
            /// the Type of item will be whatever you defined when you
            /// called ClassBuilder.AddField() (String in your example)
        }
    }
    Console.ReadLine();