write to a csv file in csharp

To write to a CSV file in C#, you can use the StreamWriter and CsvHelper libraries. The StreamWriter class allows you to write text to a file, while the CsvHelper class provides a way to write to a CSV format with ease. Here's an example:

main.cs
using CsvHelper;
using System.Globalization;
using System.IO;

//...

// Create a new CSV file and write data to it
string path = @"C:\example.csv";

using (var writer = new StreamWriter(path))
using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
{
    csv.WriteRecords(myData);
}
298 chars
15 lines

In this case, myData could be any kind of object that you want to write to the CSV file. The WriteRecords method of the CsvWriter class will automatically handle writing all of the properties of your objects to the CSV file. You can also customize the CSV writing behavior with various settings and attributes provided by the CsvHelper library.

gistlibby LogSnag