This is a rather simple and not very elegant way to generate a CSV "file", by using a string builder for efficiency.
This was used in a code base for returning an ASP MVC Controller's FileContentResult, giving a user a .csv file download of some data.
/// <summary>
/// Create a StringBuilder that contains a csv "file"
/// The first list is a list of the lines.
/// The second list inside the first list is a list of
/// strings that will seperated by a comma.
/// </summary>
/// <param name="header">A csv delimited string to be inserted first as the CSV header</param>
/// <param name="lines">A list of list of strings containing the items to be appended with a comma between values</param>
/// <returns></returns>
public static StringBuilder BuildCsv(string header, List<List<string>> lines)
{
var csvBuilder = new StringBuilder();
const string comma = ",";
csvBuilder.AppendLine(header);
foreach (var line in lines)
{
string csvLine = "";
foreach (string lineItem in line)
{
string temp = lineItem ?? "-"; // if null, give a default
//check for a comma in a string (like if the string contained "Acme, LLC"),
//then escape it so it doesnt mess up the csv formatting
if (temp.Contains(comma))
{
temp = '"' + temp + '"';
}
csvLine += temp + comma;
}
csvBuilder.AppendLine(csvLine);
}
return csvBuilder;
}