append to a csv file in csharp

To append data to a CSV file in C#, you need to open the file in append mode and write the new data to the end of the file. One way to achieve this is by using the StreamWriter class:

main.cs
using System.IO;
using System.Text;

// Path to the CSV file
string csvFilePath = "example.csv";

// Data to append (comma-separated values)
string newData = "John,Doe,45";

// Open the file in append mode and append the new data
using (StreamWriter sw = new StreamWriter(csvFilePath, true, Encoding.UTF8))
{
    sw.WriteLine(newData);
}
338 chars
15 lines

In this example, the StreamWriter is created with the file path, true (to indicate that the file should be opened in append mode), and the encoding (which is set to UTF8 in this case).

Then, the WriteLine() method is used to append the new data to the end of the file. Make sure that the new data is formatted as comma-separated values, with each value separated by a comma.

After the using block completes, the file will be closed and the changes will be saved.

gistlibby LogSnag