I would do it with a DataGridView:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Test_GridToCsv
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button_AddColumn_Click(object sender, EventArgs e)
{
string colName = string.Format("col_{0}", this.dataGridView1.Columns.Count);
this.dataGridView1.Columns.Add(colName, colName);
}
private void button_SaveAsCsv_Click(object sender, EventArgs e)
{
try
{
using (StreamWriter w = new StreamWriter(@"d:\tmp\1.csv"))
{
w.Write(this.dataGridView1.ExportToCsv(this.checkBox_IncludeHeaders.Checked));
}
MessageBox.Show("saved");
}
catch (System.ObjectDisposedException ex)
{
MessageBox.Show(ex.ToString());
throw;
}
catch (System.NotSupportedException ex)
{
MessageBox.Show(ex.ToString());
throw;
}
catch (System.IO.IOException ex)
{
MessageBox.Show(ex.ToString());
throw;
}
}
}
public static class Utils
{
public static string ExportToCsv(this DataGridView v, bool includeHeaders = false)
{
string s = string.Empty;
if (includeHeaders)
{
int c = 0;
for (; c < v.ColumnCount - 1; c++)
s += v.Columns[c].Name + ",";
s += v.Columns[c].Name + Environment.NewLine;
}
for (int r = 0; r < v.Rows.Count; r++)
{
int c = 0;
for (; c < v.Columns.Count - 1; c++)
{
s += (v[c, r].Value ?? "null") + ",";
}
s += (v[c, r].Value ?? "null") + Environment.NewLine;
}
return s;
}
}
}