Inserting CSV File Records Into Database Using ASP.NET C#

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,
      NULL,
      NULL,
      NULL,
      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 as follows.

Design view

Create a CSV file with the following records.

CSV file

Now Let us create the sample web application as follows.

  1. "Start", "All Programs", "Microsoft Visual Studio 2010".
  2. "File" "New WebSite", "C#", and "Empty WebSite" (to avoid adding a master page).
  3. Provide the website a name such as "InsertCSVFileIntoDataBase" or another as you wish and specify the location.
  4. Then right-click on Solution Explorer - "Add New Item" - Add Web Form.
  5. Drag and drop one Button and FileUploader controller onto the <form> section of the Default.aspx page.

Now the default.aspx Page source code will look 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">
        <p 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 />  
        </p>
    </form>
</body>
</html>

Create a function for Sqlconnection as.

private void connection()
{
    sqlconn = ConfigurationManager.ConnectionStrings["SqlCom"].ConnectionString;
    con = new SqlConnection(sqlconn);
}

Create a function to insert CSV file records into the database using SqlBulkCopy.

// Function to Insert Records
private void InsertCSVRecords(DataTable csvdt)
{
    connection();
    // creating object of SqlBulkCopy
    SqlBulkCopy objbulk = new SqlBulkCopy(con);
    // assigning Destination table name
    objbulk.DestinationTableName = "Employee";
    // Mapping Table column
    objbulk.ColumnMappings.Add("Name", "Name");
    objbulk.ColumnMappings.Add("City", "City");
    objbulk.ColumnMappings.Add("Address", "Address");
    objbulk.ColumnMappings.Add("Designation", "Designation");
    // inserting Datatable Records to DataBase
    con.Open();
    objbulk.WriteToServer(csvdt);
    con.Close();
}

Write the following code to read CSV File Records and call the InsertCSVRecords function on the button click as.

protected void Button1_Click(object sender, EventArgs e)
{
    // Creating object of datatable
    DataTable tblcsv = new DataTable();
    // Creating columns
    tblcsv.Columns.Add("Name");
    tblcsv.Columns.Add("City");
    tblcsv.Columns.Add("Address");
    tblcsv.Columns.Add("Designation");
    // Getting full file path of Uploaded file
    string CSVFilePath = Path.GetFullPath(FileUpload1.PostedFile.FileName);
    // Reading All text
    string ReadCSV = File.ReadAllText(CSVFilePath);
    // Splitting row after new line
    foreach (string csvRow in ReadCSV.Split('\n'))
    {
        if (!string.IsNullOrEmpty(csvRow))
        {
            // Adding each row into datatable
            tblcsv.Rows.Add();
            int count = 0;
            foreach (string FileRec in csvRow.Split(','))
            {
                tblcsv.Rows[tblcsv.Rows.Count - 1][count] = FileRec;
                count++;
            }
        }
    }
    // Calling insert Functions
    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.

 Application

Now click on the Upload button and see the records in the database table as.

 Database table

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 on 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.


Similar Articles