Insert Bulk Data From CSV File To Database Table Using SQLBulkCopy Class


In this article we will see how we can Import CSV File data to Database in ASP.NET C# usingSqlBulkCopy.

Let’s start to build the application which will process our required command.

Step 1:

Firstly, create Database if it does not already exist and then create table in which the dat is inserted after importing file data.

I Have Created a table, namely StudentCourses, and created three columns inside it.


Columns are StudentID, Name and Course which is old data after importing.

Here is the Script to create table.

  1. CREATE TABLE [dbo].[StudentCourses](
  2. [StudentID] [intNOT NULL,
  3. [Name] [varchar](500) NULL,
  4. [Course] [varchar](100) NULL,
  5. CONSTRAINT [PK_StudentCourses] PRIMARY KEY CLUSTERED
  6. (
  7. [StudentID] ASC
  8. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ONON [PRIMARY]
  9. ON [PRIMARY]
  10. GO

Before inserting Data Here is our empty table.


Step 2:

Let’s Build Interface / Markup of File Upload Control and Button.

I am also using bootstrap to make UI look good.

Here is the Full code of UI.

  1. <%@ Page Language=“C#” AutoEventWireup=“true” CodeFile=“Default.aspx.cs” Inherits=“_Default” %>
  2. <!DOCTYPE html>
  3. <html xmlns=http://www.w3.org/1999/xhtml&#8221;>
  4. <head runat=“server”>
  5. <title></title>
  6. http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js”&gt;
  7. <link rel=“stylesheet” href=http://netdna.bootstrapcdn.com/bootstrap/3.0.2/css/bootstrap.min.css&#8221; />
  8. http://netdna.bootstrapcdn.com/bootstrap/3.0.2/js/bootstrap.min.js”&gt;
  9. </head>
  10. <body>
  11. <form id=“form1” runat=“server”>
  12. class=“form-horizontal” style=“margin-top:50px”>
  13. class=“form-group”>
  14. class=“col-lg-3 control-label”>Upload CSV File
  15. class=“col-lg-5”>
  16. “fupcsv” runat=“server” />
  • </div>
  • class=“form-group”>
  • class=“col-lg-9 col-lg-offset-3”>
  • “btnimportcsv” runat=“server” Text=“>Import CSV Data to SQL Table” OnClick=“btnimportcsv_Click” />
  • </div>
  • </div>
  • </form>
  • </body>
  • </html>
  • Step 3:

    Before starting we will create the connection string in web.config. Today I will introduce you the best connection string generator method which can reduce the error and it also test the connection as well. Right Click on your PC Desktop it will open the context menu Now Choose New è Text Document, New text documents created now change the extension of text file from .txt to .udl and Hit Enter.

    It will show prompt like this just press to continue and extension of the file has been changed.

    Now double click the file to open it will look like this.

    Now fill in the desired information in respective fields and test the connection it will give you prompt of failure or success.

    Now press ok at the prompt and then finally hit the OK button of Data Link Properties Window. If you have selected check box of Allow saving password it will give you confirmation message” are you sure?”

    After selecting yes it will print the saved password to the file. Now we will check how it looks like our connection string. Right click the data link properties file and open it with Notepad. It will show you this final oledb connection string.

    And that’s all to generate connection string.

    Step 4:

    So we will start to firstly check the valid .csv extension file and Upload to the certain path.

    1. string fileExt = Path.GetExtension(fupcsv.PostedFile.FileName);
    2. if (fileExt == “.csv”)
    3. {
    4. string csvPath = Server.MapPath(“~/CSVFIles/”) + Path.GetFileName(fupcsv.PostedFile.FileName);
    5. fupcsv.SaveAs(csvPath);
    6. }
    7. else
    8. {
    9. lblmessage.Text = “Please upload valid .csv extension file”;
    10. lblmessage.ForeColor = System.Drawing.Color.Red;
    11. }

    Firstly, checked the file Extension by using the Path.GetExtension () Method and the we have save the file to Certain path by using Server.MapPath to assign path and then use SaveAs() Method to upload it to the Path.

    Step 5:

    In this step we will do our code behind functionality to firstly upload to the certain path and then read the file using File.ReadAllText() Method. After that a connection has been established with the database and we will use SqlBulkCopy Class to define our destination table and write to the database using WriteToServer() Method of SqlBulkCopy Class to finish the task.

    Here is the full code which can do our desired task, Code Comments are added for well understanding.

    1. string fileext = Path.GetExtension(fupcsv.PostedFile.FileName);
    2. if (fileext == “.csv”)
    3. {
    4. string csvPath = Server.MapPath(“~/CSVFIles/”) + Path.GetFileName(fupcsv.PostedFile.FileName);
    5. fupcsv.SaveAs(csvPath);
    6. // Add Columns to Datatable to bind data
    7. DataTable dtCSV = new DataTable();
    8. dtCSV.Columns.AddRange(new DataColumn[3] { new DataColumn(“StudentID”typeof(int)),
    9. new DataColumn(“Name”typeof(string)),
    10. new DataColumn(“Course”,typeof(string)) });
    11. // Read all the lines of the text file and close it.
    12. string csvData = File.ReadAllText(csvPath);
    13. // iterate over each row and Split it to New line.
    14. foreach (string row in csvData.Split(‘\n’))
    15. {
    16. // Check for is null or empty row record
    17. if (!string.IsNullOrEmpty(row))
    18. {
    19. // added rows
    20. dtCSV.Rows.Add();
    21. int i = 1;
    22. foreach (string cell in row.Split(‘,’))
    23. {
    24. dtCSV.Rows[dtCSV.Rows.Count – 1][i] = cell;
    25. i++;
    26. }
    27. }
    28. }
    29. // Database connection string
    30. string consString = ConfigurationManager.ConnectionStrings[“GamesConnectionString”].ConnectionString;
    31. using (SqlConnection con = new SqlConnection(consString))
    32. {
    33. // class use to bulk load data from another source
    34. using (SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(con))
    35. {
    36. // Set the database table name in which data to be added
    37. sqlBulkCopy.DestinationTableName = “dbo.StudentCourses”;
    38. con.Open();
    39. // copy all the rows from dataTable to the destination Database table.
    40. sqlBulkCopy.WriteToServer(dtCSV);
    41. con.Close();
    42. lblmessage.Text = “Bulk Data Successfully dump into the Destination table”;
    43. lblmessage.ForeColor = System.Drawing.Color.Green;
    44. }
    45. }
    46. }
    47. else
    48. {
    49. lblmessage.Text = “Please upload valid .csv extesnion file”;
    50. lblmessage.ForeColor = System.Drawing.Color.Red;
    51. }
    52. }

    After this line of code we get success message which assures us that our data dumped successfully.

    Step 6: Output of the CSV to Database Table.