In general you can achieve it in two steps
1) step is to read the CSV file and hold it as a DataTable.
2) step Store the retrieved file into SQL Table as a Bulk Entry
2) step Store the retrieved file into SQL Table as a Bulk Entry
This is a function that returns CSV File Data as a Datatable. call and get it, and in the end do whatever you want
This function is going to return CSV Read file into DataTable.
private static DataTable GetDataTabletFromCSVFile(string csv_file_path)
{
DataTable csvData = new DataTable();
try
{
using(TextFieldParser csvReader = new TextFieldParser(csv_file_path))
{
csvReader.SetDelimiters(new string[] { "," });
csvReader.HasFieldsEnclosedInQuotes = true;
string[] colFields = csvReader.ReadFields();
foreach (string column in colFields)
{
DataColumn datecolumn = new DataColumn(column);
datecolumn.AllowDBNull = true;
csvData.Columns.Add(datecolumn);
}
while (!csvReader.EndOfData)
{
string[] fieldData = csvReader.ReadFields();
//Making empty value as null
for (int i = 0; i < fieldData.Length; i++)
{
if (fieldData[i] == "")
{
fieldData[i] = null;
}
}
csvData.Rows.Add(fieldData);
}
}
}
catch (Exception ex)
{
}
return csvData;
}
SQLBulkCopy - Use this function to insert the Retrieved DataTable into Sql Table
protected void InsertDataIntoSQLServerUsingSQLBulkCopy(DataTable csvFileData)
{
Con.Open();
using (SqlBulkCopy s = new SqlBulkCopy(dbConnection))
{
s.DestinationTableName = "Your table name";
foreach (var column in csvFileData.Columns)
s.ColumnMappings.Add(column.ToString(), column.ToString());
s.WriteToServer(csvFileData);
}
Con.Close();
}
Ref:
http://www.morgantechspace.com/2013/10/import-csv-file-into-sql-server-using.html