I am trying to read a CSV file with CsvHelper, load each record into a DataTable, and then use SqlBulkCopy to insert the data into a database table. With the current code, I get
Josh added support to read headers last year and the following block may be useful to those who just want to build a DataTable using the schema of the CSV document. I wanted to post this as a comment to Josh's answer as it is only a small modification but posting as an answer as I couldn't format a code block in Comments.
private DataTable BuildDataTable()
{
var dt = new DataTable();
using (var textReader = new StreamReader(_path))
{
using (var csv = new CsvReader(textReader))
{
csv.ReadHeader();
foreach (var header in csv.FieldHeaders)
{
dt.Columns.Add(header);
}
while (csv.Read())
{
var row = dt.NewRow();
foreach (DataColumn column in dt.Columns)
{
row[column.ColumnName] = csv.GetField(column.DataType, column.ColumnName);
}
dt.Rows.Add(row);
}
}
}
return dt;
}