Skip to content

Instantly share code, notes, and snippets.

@ArtemAvramenko
Last active August 29, 2015 14:19
Show Gist options
  • Save ArtemAvramenko/fef1f0ad30f8f2e8d3f7 to your computer and use it in GitHub Desktop.
Save ArtemAvramenko/fef1f0ad30f8f2e8d3f7 to your computer and use it in GitHub Desktop.
C# CSV writer
public delegate void ValuesGetter(params Object[] values);
private const char Comma = ',';
private static readonly Regex _escapedChars = new Regex(@"[,""\r\n]");
public static string ToCsv<T>(IEnumerable<T> enumerable, string headers, Action<T, ValuesGetter> valuesGetter)
{
var columnCount = headers.Count(c => c == Comma) + 1;
var result = new StringBuilder();
result.AppendLine(headers);
ValuesGetter callback = values =>
{
if (values == null)
{
throw new ArgumentNullException("values");
}
if (values.Length != columnCount)
{
throw new ArgumentException("values");
}
isFirst = true;
foreach (var value in values)
{
if (isFirst)
{
isFirst = false;
}
{
result.Append(Comma);
}
if (value != null)
{
var text = string.Format(CultureInfo.InvariantCulture, "{0}", value);
if (_escapedChars.IsMatch(text))
{
text = "\"" + text.Replace("\"", "\"\"") + "\"";
}
result.Append(text);
}
}
};
foreach (var item in enumerable)
{
valuesGetter(item, callback);
result.AppendLine();
}
return result.ToString();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment