To create a csv file we will use “StringBuilder” and “WriteAllText” functions. It use these functions we need to add two namespaces.
- System.Text (StringBuilder)
- System.IO (WriteAllText)
This is a very simple way to write a CSV (Comma separated value) file. You can use this file type to export and import data between applications.
I recommend you use this format in your export options when you are developing something.
private static void Csv(List<Element> elements) { var csv = new StringBuilder(); string head = "Field1,Field2,Field3"; csv.AppendLine(head); foreach (var element in elements) { string line = element.field1 + ";" + element.field2 + ";" + element.field3; csv.AppendLine(line); } File.WriteAllText("data.csv", csv.ToString()); }
More information about CSV file: https://en.wikipedia.org/wiki/Comma-separated_values