Showing posts with label Read CSV file and Insert In to Data Base Asp.Net Bulk Insert Asp.Net Read CSV file SqlBulkCopy Read CSV file and Insert. Show all posts
Showing posts with label Read CSV file and Insert In to Data Base Asp.Net Bulk Insert Asp.Net Read CSV file SqlBulkCopy Read CSV file and Insert. Show all posts

Saturday, 5 July 2014

C# Read CSV file and Insert In to Data Base

using System.IO;
DataTable dt = new DataTable();
string line = null;
int i = 0;
using (StreamReader sr = File.OpenText(@"c:\t.csv"))
{
while ((line = sr.ReadLine()) != null)
{
string[] data = line.Split(',');
if (data.Length > 0)
{
if (i == 0)
{
foreach (var item in data)
{
dt.Columns.Add(new DataColumn());
}
i++;
}
DataRow row = dt.NewRow();
row.ItemArray = data;
dt.Rows.Add(row);
//GridView1.DataSource = dt;
//GridView1.DataBind();
}
}
}
//Insert in to db
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConsoleApplication3.Properties.Settings.daasConnectionString"].ConnectionString))
{
conn.Open();
using (SqlBulkCopy copy = new SqlBulkCopy(conn))
{
copy.ColumnMappings.Add(0, 0);
copy.ColumnMappings.Add(1, 1);
copy.ColumnMappings.Add(2, 2);
copy.ColumnMappings.Add(3, 3);
copy.ColumnMappings.Add(4, 4);
//Table Name.
copy.DestinationTableName = "Censis";
copy.WriteToServer(dt);
}
}