Background
I have often read the common question in forum posts, how to upload CSV file records into a database but no one has provided the proper solution and many solutions contain a lot of code that is not required so by considering the preceding requirements I have decided to write this article to provide the solution to insert CSV file records into the database with a minimum amount of code. So let us start creating an application so beginners can also understand.
First create the table named Employee using the following script:
- CREATE TABLE [dbo].[Employee](
- [id] [int] IDENTITY(1,1) NOT NULL,
- [Name] [varchar](50) NULL,
- [City] [varchar](50) NULL,
- [Address] [varchar](50) NULL,
- [Designation] [varchar](50) NULL,
- CONSTRAINT [PK_Employee] PRIMARY KEY CLUSTERED
- (
- [id] ASC
- )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
- ) ON [PRIMARY]
Then the design view of the table will look such as follows
Create the some CSV file with the following records
Now Let us create the sample web application as follows:
- "Start" - "All Programs" - "Microsoft Visual Studio 2010".
- "File" - "New WebSite" - "C#" - "Empty WebSite" (to avoid adding a master page).
- Provide the web site a name such as "InsertCSVFileIntoDataBase" or another as you wish and specify the location.
- Then right-click on Solution Explorer - "Add New Item" - Add Web Form.
- Drag and drop one Button and FileUploader controler onto the <form> section of the Default.aspx page.
Now the default.aspx Page source code will look such as follows.
- <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
-
- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
-
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head id="Head1" runat="server">
- <title>Article by Vithal Wadje</title>
- </head>
- <body bgcolor="gray">
- <form id="form1" runat="server">
- <div style="color: White;">
- <h4>
- Article for C#Corner
- </h4>
- <table>
- <tr>
- <td>
- Select File
- </td>
- <td>
- <asp:FileUpload ID="FileUpload1" runat="server" />
- </td>
- <td>
- </td>
- <td>
- <asp:Button ID="Button1" runat="server" Text="Upload" OnClick="Button1_Click" />
- </td>
- </tr>
- </table> <br /><br />
-
- </div>
-
- </form>
- </body>
- </html>
Create a function for Sqlconnection as:
- private void connection()
- {
- sqlconn = ConfigurationManager.ConnectionStrings["SqlCom"].ConnectionString;
- con = new SqlConnection(sqlconn);
-
- }
Create function to insert CSV file records into database using SqlBulkCopy as:
-
- private void InsertCSVRecords(DataTable csvdt)
- {
-
- connection();
-
- SqlBulkCopy objbulk = new SqlBulkCopy(con);
-
- objbulk.DestinationTableName = "Employee";
-
- objbulk.ColumnMappings.Add("Name", "Name");
- objbulk.ColumnMappings.Add("City", "City");
- objbulk.ColumnMappings.Add("Address", "Address");
- objbulk.ColumnMappings.Add("Designation", "Designation");
-
- con.Open();
- objbulk.WriteToServer(csvdt);
- con.Close();
-
-
- }
Write the following code to read CSV File Records and call InsertCSVRecords function on button click as
- protected void Button1_Click(object sender, EventArgs e)
- {
-
- DataTable tblcsv = new DataTable();
-
- tblcsv.Columns.Add("Name");
- tblcsv.Columns.Add("City");
- tblcsv.Columns.Add("Address");
- tblcsv.Columns.Add("Designation");
-
- string CSVFilePath = Path.GetFullPath(FileUpload1.PostedFile.FileName);
-
- string ReadCSV = File.ReadAllText(CSVFilePath);
-
- foreach (string csvRow in ReadCSV.Split('\n'))
- {
- if (!string.IsNullOrEmpty(csvRow))
- {
-
- tblcsv.Rows.Add();
- int count = 0;
- foreach (string FileRec in csvRow.Split(','))
- {
- tblcsv.Rows[tblcsv.Rows.Count - 1][count] = FileRec;
- count++;
- }
- }
-
-
- }
-
- InsertCSVRecords(tblcsv);
- }
The entire code of the default.aspx.cs page will look as follows:
- using System;
- using System.IO;
- using System.Data;
- using System.Data.SqlClient;
- using System.Configuration;
- public partial class _Default : System.Web.UI.Page
- {
-
- SqlConnection con;
-
- string sqlconn;
- protected void Page_Load(object sender, EventArgs e)
- {
-
-
- }
-
-
- private void connection()
- {
- sqlconn = ConfigurationManager.ConnectionStrings["SqlCom"].ConnectionString;
- con = new SqlConnection(sqlconn);
-
- }
-
- protected void Button1_Click(object sender, EventArgs e)
- {
-
- DataTable tblcsv = new DataTable();
-
- tblcsv.Columns.Add("Name");
- tblcsv.Columns.Add("City");
- tblcsv.Columns.Add("Address");
- tblcsv.Columns.Add("Designation");
-
- string CSVFilePath = Path.GetFullPath(FileUpload1.PostedFile.FileName);
-
- string ReadCSV = File.ReadAllText(CSVFilePath);
-
- foreach (string csvRow in ReadCSV.Split('\n'))
- {
- if (!string.IsNullOrEmpty(csvRow))
- {
-
- tblcsv.Rows.Add();
- int count = 0;
- foreach (string FileRec in csvRow.Split(','))
- {
- tblcsv.Rows[tblcsv.Rows.Count - 1][count] = FileRec;
- count++;
- }
- }
-
-
- }
-
- InsertCSVRecords(tblcsv);
- }
-
- private void InsertCSVRecords(DataTable csvdt)
- {
-
- connection();
-
- SqlBulkCopy objbulk = new SqlBulkCopy(con);
-
- objbulk.DestinationTableName = "Employee";
-
- objbulk.ColumnMappings.Add("Name", "Name");
- objbulk.ColumnMappings.Add("City", "City");
- objbulk.ColumnMappings.Add("Address", "Address");
- objbulk.ColumnMappings.Add("Designation", "Designation");
-
- con.Open();
- objbulk.WriteToServer(csvdt);
- con.Close();
-
-
- }
- }
-
Now run the application and upload the file as follows
Now click on the Upload button and see the records in the database table as
Now you have seen how the records are inserted into the database with minimal code and effort.
Notes
- For detailed code please download the sample Zip file.
- Do a proper validation such as date input values when implementing.
- Make the changes in the web.config file depending on your server details for the connection string.
Summary
From all the preceding examples you have learned how to insert CSV File records into the database. I hope this article is useful for all readers, if you have a suggestion then please contact me.