Search code examples
c#.netfilehelpers

DataTable from FileHelpers Class -- type.GetProperties() returns empty array


I've successfully pulled a CSV file into the following class:

[DelimitedRecord(",")]
[IgnoreFirst(1)] // ignores first line of file, since it's a header
public class Employee {
    public string EmployeeId;
    public string FirstName;
    public string LastName;
    // etc.
}

I need to create a DataTable based on that class in order to use SqlBulkCopy. I've found several examples, but the following method doesn't work for me:

private static DataTable createEmptyDataTable(Type myType) {
        DataTable dt = new DataTable();

        foreach (PropertyInfo info in myType.GetProperties()) {
            dt.Columns.Add(new DataColumn(info.Name, info.PropertyType));
        }

        return dt;
    }

The problem is with myType.GetProperties(). It's not throwing an error, but it returns nothing. The PropertyInfo array that it should return is empty. Been at this a while and can't figure out the problem...

EDIT: I've also used this variant with no success:

private static DataTable createEmptyDataTable(Type myType) {
        DataTable dt = new DataTable();
        PropertyInfo[] infoArray = myType.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static);

        foreach (PropertyInfo info in infoArray) {
            dt.Columns.Add(new DataColumn(info.Name, info.PropertyType));
        }

        return dt;
    }

Solution

  • Your Employee class contains fields, not properties. Use rather

    myType.GetFields()