Here is a nice little extension that will take an object and convert it into a CSV file.
Also has the option if you want to include a header on the CSV file.
public static class ObjectToCsv
{
public static string ToCsv<T>(this IEnumerable<T> items, bool includeHeading = true)
where T : class
{
var csvBuilder = new StringBuilder();
var properties = typeof(T).GetProperties();
if (includeHeading)
{
csvBuilder.AppendLine(string.Join(",", properties.Select(p => p.Name.ToCsvValue()).ToArray()));
}
foreach (var item in items)
{
var line = string.Join(",", properties.Select(p => p.GetValue(item, null).ToCsvValue()).ToArray());
csvBuilder.AppendLine(line);
}
return csvBuilder.ToString();
}
private static string ToCsvValue<T>(this T item)
{
if (item == null) return "\"\"";
if (item is string)
{
return $"\"{item.ToString().Replace("\"", "\\\"")}\"";
}
double dummy;
return double.TryParse(item.ToString(), out dummy) ? $"{item}" : $"\"{item}\"";
}
}