1

I'm trying to use System.Reflection to output a first row of column header information for a csv text file before I create the actual generic List from my data source.

public class DocMetaData
{
    public const string SEPARATOR = "\t";       // horizontal tab is delimiter
    public string Comment { get; set; }
    public string DocClass { get; set; }
    public string Title { get; set; }
    public string Folder { get; set; }
    public string File { get; set; }
}

In the following routine, I am trying to loop through the properties of the object definition and use the property name as a "column name" for my first row of my output file:

private void OutputColumnNamesAsFirstLine(StreamWriter writer)
    {
        StringBuilder md = new StringBuilder();
        PropertyInfo[] columns;
        columns = typeof(DocMetaData).GetProperties(BindingFlags.Public |
                                                      BindingFlags.Static);
        foreach (var columnName in columns)
        {
            md.Append(columnName.Name); md.Append(DocMetaData.SEPARATOR);
        }
        writer.WriteLine(md.ToString());
    }

The foreach loop exits immediately. Also, I put a constant separator in the class but I want to use that as a field separator value (rather than as a "column" name).

I am assuming that the ordinal position of the properties in the class will be maintained consistently if I can get something like this to work.

The remainder of the code which creates the List<DocMetaData> from my data source works but I'd like to add this "first row" stuff.

Thank you for help on this.

John Adams
  • 4,773
  • 25
  • 91
  • 131

3 Answers3

3

Don't use BindingFlags.Static because that yields only static members (public static). Use BindingFlag.Instance instead, since your properties are instance members.

agent-j
  • 27,335
  • 5
  • 52
  • 79
3

I suppose you have to do

columns = typeof(DocMetaData).GetProperties(BindingFlags.Public |
                                                      BindingFlags.Instance);

The fields you are trying to search are instance fields not static

ata
  • 8,853
  • 8
  • 42
  • 68
2

You should replace BindingFlags.Static with BindingFlags.Instance. The properties in yourDocMetaData` are not static.

private void OutputColumnNamesAsFirstLine(StreamWriter writer)
{
    StringBuilder md = new StringBuilder();
    PropertyInfo[] columns;
    columns = typeof(DocMetaData).GetProperties(BindingFlags.Public |
                                                  BindingFlags.Instance);
    foreach (var columnName in columns)
    {
        md.Append(columnName.Name); 
        md.Append(DocMetaData.SEPARATOR);
    }
    writer.WriteLine(md.ToString());
}
Jan-Peter Vos
  • 3,157
  • 1
  • 18
  • 21