Upload to SQL via Bulk Copy in .Net
/// <summary>
/// Write data to DB
/// </summary>
/// <param name="tableName">Name of SQL Table to Perform Insert on as <see cref="string"/></param>
/// <param name="fileData">Data to Insert as <see cref="DataTable"/></param>
/// <remarks>fileData should have column names that match Sql table or custom mapping changes will be needed.</remarks>
static void InsertDataIntoSqlServerUsingSqlBulkCopy(string tableName, DataTable fileData)
{
Log(string.Format("Inserting {0} Records into {1} \n\n", fileData.Rows.Count.ToString("###,###,##0"), tableName));
using (var dbConnection = new SqlConnection(DbConnectionString))
{
dbConnection.Open();
using (var s = new SqlBulkCopy(dbConnection))
{
s.BulkCopyTimeout = 60;
s.BatchSize = 5000;
s.DestinationTableName = tableName;
foreach (var column in fileData.Columns)
s.ColumnMappings.Add(column.ToString(), column.ToString());
s.WriteToServer(fileData);
}
}
}