我编写了一个将数据表保存为 CSV 文件格式的函数。但问题是,当我调用该函数时,该函数会删除旧数据并写入新数据。我只想保留旧数据并在文件末尾写入新数据。我怎样才能做到这一点?我的功能是:
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());
}