How can I load a CSV file into a System.Data.DataTable
, creating the datatable based on the CSV file?
Does the regular ADO.net functionality allow this?
Just sharing this extension methods, I hope that it can help someone.
public static List ToCSV(this DataSet ds, char separator = '|')
{
List lResult = new List();
foreach (DataTable dt in ds.Tables)
{
StringBuilder sb = new StringBuilder();
IEnumerable columnNames = dt.Columns.Cast().
Select(column => column.ColumnName);
sb.AppendLine(string.Join(separator.ToString(), columnNames));
foreach (DataRow row in dt.Rows)
{
IEnumerable fields = row.ItemArray.Select(field =>
string.Concat("\"", field.ToString().Replace("\"", "\"\""), "\""));
sb.AppendLine(string.Join(separator.ToString(), fields));
}
lResult.Add(sb.ToString());
}
return lResult;
}
public static DataSet CSVtoDataSet(this List collectionCSV, char separator = '|')
{
var ds = new DataSet();
foreach (var csv in collectionCSV)
{
var dt = new DataTable();
var readHeader = false;
foreach (var line in csv.Split(new[] { Environment.NewLine }, StringSplitOptions.None))
{
if (!readHeader)
{
foreach (var c in line.Split(separator))
dt.Columns.Add(c);
}
else
{
dt.Rows.Add(line.Split(separator));
}
}
ds.Tables.Add(dt);
}
return ds;
}