The original class have a problem, and that is if you want to add a new column, you will receive KeyNotFoundException on Export method. For example:
static void Main(string[] args)
{
var export = new CsvExport();
export.AddRow();
export["Region"] = "New York, USA";
export["Sales"] = 100000;
export["Date Opened"] = new DateTime(2003, 12, 31);
export.AddRow();
export["Region"] = "Sydney \"in\" Australia";
export["Sales"] = 50000;
export["Date Opened"] = new DateTime(2005, 1, 1, 9, 30, 0);
export["Balance"] = 3.45f; //Exception is throwed for this new column
export.ExportToFile("Somefile.csv");
}
To solve this, and using the @KeyboardCowboy idea of using reflection, I modified the code to allow add rows that do not have the same columns. You can use instances of anonymous classes. For example:
static void Main(string[] args)
{
var export = new CsvExporter();
export.AddRow(new {A = 12, B = "Empty"});
export.AddRow(new {A = 34.5f, D = false});
export.ExportToFile("File.csv");
}
You can download the source code here CsvExporter. Feel free to use and modify.
Now, if all rows you want to write are of the same class, I created the generic class CsvWriter.cs, which has a better performance RAM usage and ideal for writing large files.Plus it lets you add formatters to the data type you want. An example of use:
class Program
{
static void Main(string[] args)
{
var writer = new CsvWriter<Person>("Persons.csv");
writer.AddFormatter<DateTime>(d => d.ToString("MM/dd/yyyy"));
writer.WriteHeaders();
writer.WriteRows(GetPersons());
writer.Flush();
writer.Close();
}
private static IEnumerable<Person> GetPersons()
{
yield return new Person
{
FirstName = "Jhon",
LastName = "Doe",
Sex = 'M'
};
yield return new Person
{
FirstName = "Jhane",
LastName = "Doe",
Sex = 'F',
BirthDate = DateTime.Now
};
}
}
class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public char Sex { get; set; }
public DateTime BirthDate { get; set; }
}