By using reflection you can retrieve the property infos from an object
foreach (PropertyInfo prp in obj.GetType().GetProperties()) {
if (prp.CanRead) {
object value = prp.GetValue(obj, null);
string s = value == null ? "" : value.ToString();
string name = prp.Name;
...
}
}
The GetProperties
method has an overload accepting BindingFlags
through which you can determine which kind of property you need, like private/public instance/static.
You can combine them like this
var properties = type.GetProperties(BindingFlags.Public |
BindingFlags.NonPublic |
BindingFlags.Instance);
Applied to your problem you could write
List<Person> people = ...;
Type type = typeof(Person);
PropertyInfo[] properties = type.GetProperties();
var sb = new StringBuilder();
// First line contains field names
foreach (PropertyInfo prp in properties) {
if (prp.CanRead) {
sb.Append(prp.Name).Append(';');
}
}
sb.Length--; // Remove last ";"
sb.AppendLine();
foreach (Person person in people) {
foreach (PropertyInfo prp in properties) {
if (prp.CanRead) {
sb.Append(prp.GetValue(person, null)).Append(';');
}
}
sb.Length--; // Remove last ";"
sb.AppendLine();
}
File.AppendAllText("C:\Data\Persons.csv", sb.ToString());
It is also a good idea to enclose strings in double quotes and to escape doubles quotes they contain by doubling them.