How can I write all values (properties) into an csv formated string in C#? e.g.:
class Person(string firstName, string lastName, int_age);
Person person = new Person("Kevin","Kline",33);
now I want a string "Kevin;Kline;33"
In other words I want to serialize an object into CSV
Have a look at Josh Close's excellent CSVHelper library
var person = new Person("Kevin","Kline",33);
using (var csv = new CsvWriter(new StreamWriter("file.csv")))
{
csv.Configuration.HasHeaderRecord = false;
csv.Configuration.Delimiter = ';';
csv.WriteRecord(person);
}
Output:
Kevin;Kline;33
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.
you can use something like this:
...
PropertyInfo[] properties = obj.GetType().GetProperties();
string CSVRow = "";
foreach (PropertyInfo pi in properties)
{
CSVRow = CSVRow + pi.GetValue(obj, null) + ";";
}
CSVRow.Remove(CSVRow.Length - 1, 1);
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With