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)
开发者_C百科 {
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.
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
Don't use BindingFlags.Static
because that yields only static members (public static). Use BindingFlag.Instance
instead, since your properties are instance members.
You should replace BindingFlags.Static
with BindingFlags.Instance. The properties in your
DocMetaData` 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());
}
精彩评论