create a csv file in csharp

To create a CSV file in C#, you can use the StreamWriter class along with a delimiter. Here's an example:

main.cs
using System.IO;

class Program
{
    static void Main(string[] args)
    {
        // create a new CSV file and add some data
        using (StreamWriter file = new StreamWriter("example.csv"))
        {
            file.WriteLine("Name, Age, Gender"); // header
            file.WriteLine("John Smith, 25, Male"); // data
            file.WriteLine("Jane Doe, 30, Female"); // data
        }
    }
}
402 chars
16 lines

In this example, we create a new CSV file called example.csv and add some data to it. We use StreamWriter to write to the file, and use file.WriteLine to write each line of text. The first line is the header, followed by two lines of data. The delimiter used in this example is a comma.

Note that this example writes the contents of the CSV file from scratch. If you already have data that needs to be added to an existing CSV file, you would need to use a different approach such as reading the existing file into memory, adding the new data to it, and then writing it back to the file.

gistlibby LogSnag