Search code examples
c#reflectionfilehelpers

How do you access an object whose type is defined at run-time?


I am using FileHelpers to parse CSV files whose structure is unknown using the following code:

            string cd = string.Format(@"[DelimitedRecord(""{0}"")]
                                        public sealed class ImportClass {{
                                            [FieldQuoted('{1}')]
                                            public string[] Fields;
                                        }}", _delimiter, _quote);
            Type t = DelimitedClassBuilder.ClassFromString(cd);

            var engine = new FileHelperAsyncEngine(t);

            engine.BeginReadFile(filename);
            object record;
            while ((record = engine.ReadNext()) != null) {

            }

            engine.Close();

This seems to work just fine. When I step through it with the debugger, record is an object of type ImportClass and the Fields field is correctly filled with data from the file.

The problem I have is how do I actually extract that data? I cant cast record to an ImportClass since that type is not known at compile time. Do I really need to use reflection or is there a simpler way to do this?


Solution

  • There's probably a clean way of doing this exposed by the library you're using. Nevertheless, here is a general answer using Reflection:

    Type t = ...  // You already have this
    PropertyInfo fieldsProperty = t.GetProperty("Fields",
        BindingFlags.Public | BindingFlags.Instance);
    string[] fields = (string[])fieldsProperty.GetValue(record, null);
    

    Edit:

    This library appears to have methods that allow you to read the file into a DataTable instead, and this seems to be their recommended approach. The example shown on this page is:

    DataTable dt = engine.ReadFileAsDT("test.txt"); 
    

    This is probably simpler and faster than using Reflection.