Skip to content

Instantly share code, notes, and snippets.

@sinairv
Last active August 29, 2015 14:16
Show Gist options
  • Save sinairv/3a46f00823fabd4cb137 to your computer and use it in GitHub Desktop.
Save sinairv/3a46f00823fabd4cb137 to your computer and use it in GitHub Desktop.
A simple implementation of a CSV Writer in C#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Text;
namespace Utilities
{
public class CsvWriter
{
public static string ToCsv<T>(IEnumerable<T> objectsToExport)
{
var sb = new StringBuilder();
var props = typeof (T).GetProperties(BindingFlags.GetProperty | BindingFlags.Public | BindingFlags.Instance);
for (int i = 0; i < props.Length; i++)
{
var prop = props[i];
if (i > 0)
{
sb.Append(",");
}
string propertyName = prop.Name;
var firstDescription = prop.GetCustomAttributes(typeof (DescriptionAttribute), true).Cast<DescriptionAttribute>().FirstOrDefault();
if (firstDescription != null && !String.IsNullOrWhiteSpace(firstDescription.Description))
propertyName = firstDescription.Description.Trim();
sb.Append(Enquote(propertyName));
}
sb.AppendLine();
foreach (var obj in objectsToExport)
{
for (int i = 0; i < props.Length; i++)
{
var prop = props[i];
if (i > 0)
{
sb.Append(",");
}
object propertyValue = prop.GetValue(obj, null);
sb.Append(Enquote(propertyValue.ToString()));
}
sb.AppendLine();
}
return sb.ToString();
}
private static string Enquote(string value)
{
string result = value ?? String.Empty;
if (result.Contains("\"") || result.Contains(",") || result.Contains("\r") || result.Contains("\n"))
{
result = String.Concat("\"", result.Replace("\"","\"\""), "\"");
}
return result;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment