I wrote a function to Save datatable to CSV file format. But problem is that function remove old data and write new data when i call the function. I just want to keep my old data and write new data end of the file. How can I do that? My function is:
public void CreateCSVFile(DataTable dt, string strFilePath, bool isFirstRowHeader)
{
StringBuilder sb = new StringBuilder();
if (isFirstRowHeader == true)
{
var columnNames = dt.Columns.Cast<DataColumn>().Select(column => column.ColumnName).ToArray();
sb.AppendLine(string.Join(",", columnNames));
}
foreach (DataRow row in dt.Rows)
{
var fields = row.ItemArray.Select(field => field.ToString()).ToArray();
sb.AppendLine(string.Join(",", fields));
}
File.WriteAllText(strFilePath, sb.ToString());
}
File.AppendAllTextinstead ofFile.WriteAllTextwill append to the end of your existing CSV file. You’ll need to avoid writing out the headers if the file exists already, of course.