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# using SqlBulkCopy.

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.   
  3. [StudentID] [intNOT NULL,  
  4.   
  5. [Name] [varchar](500) NULL,  
  6.   
  7. [Course] [varchar](100) NULL,  
  8.   
  9. CONSTRAINT [PK_StudentCourses] PRIMARY KEY CLUSTERED  
  10.   
  11. (  
  12.   
  13. [StudentID] ASC  
  14.   
  15. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ONON [PRIMARY]  
  16.   
  17. ON [PRIMARY]  
  18.   
  19. 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.   
  3. <!DOCTYPE html>  
  4.   
  5. <html xmlns="http://www.w3.org/1999/xhtml">  
  6.   
  7. <head runat="server">  
  8.   
  9. <title></title>  
  10.   
  11. <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>  
  12.   
  13. <link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.0.2/css/bootstrap.min.css" />  
  14.   
  15. <script src="http://netdna.bootstrapcdn.com/bootstrap/3.0.2/js/bootstrap.min.js"></script>  
  16.   
  17. </head>  
  18.   
  19. <body>  
  20.   
  21. <form id="form1" runat="server">  
  22.   
  23. <div class="form-horizontal" style="margin-top:50px">  
  24.   
  25. <div class="form-group">  
  26.   
  27. <label class="col-lg-3 control-label">Upload CSV File</label>  
  28.   
  29. <div class="col-lg-5">  
  30.   
  31. <asp:FileUpload ID="fupcsv" runat="server" />  
  32.   
  33. </div>  
  34.   
  35. </div>  
  36.   
  37. <div class="form-group">  
  38.   
  39. <div class="col-lg-9 col-lg-offset-3">  
  40.   
  41. <asp:Button ID="btnimportcsv" runat="server" Text=">Import CSV Data to SQL Table" OnClick="btnimportcsv_Click" />  
  42.   
  43.   
  44. </div>  
  45.   
  46. </div>  
  47.   
  48. </div>  
  49.   
  50. </form>  
  51.   
  52. </body>  
  53.   
  54. </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.   
  3. if (fileExt == ".csv")  
  4.   
  5. {  
  6.   
  7. string csvPath = Server.MapPath("~/CSVFIles/") + Path.GetFileName(fupcsv.PostedFile.FileName);  
  8.   
  9. fupcsv.SaveAs(csvPath);  
  10.   
  11. }  
  12.   
  13. else  
  14.   
  15. {  
  16.   
  17. lblmessage.Text = "Please upload valid .csv extension file";  
  18.   
  19. lblmessage.ForeColor = System.Drawing.Color.Red;  
  20.   
  21. }   

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.   
  3. if (fileext == ".csv")  
  4.   
  5. {  
  6.   
  7. string csvPath = Server.MapPath("~/CSVFIles/") + Path.GetFileName(fupcsv.PostedFile.FileName);  
  8.   
  9. fupcsv.SaveAs(csvPath);  
  10.   
  11. // Add Columns to Datatable to bind data  
  12.   
  13. DataTable dtCSV = new DataTable();  
  14.   
  15. dtCSV.Columns.AddRange(new DataColumn[3] { new DataColumn("StudentID"typeof(int)),  
  16.   
  17. new DataColumn("Name"typeof(string)),  
  18.   
  19. new DataColumn("Course",typeof(string)) });  
  20.   
  21. // Read all the lines of the text file and close it.  
  22.   
  23. string csvData = File.ReadAllText(csvPath);  
  24.   
  25. // iterate over each row and Split it to New line.  
  26.   
  27. foreach (string row in csvData.Split('\n'))  
  28.   
  29. {  
  30.   
  31. // Check for is null or empty row record  
  32.   
  33. if (!string.IsNullOrEmpty(row))  
  34.   
  35. {  
  36.   
  37. // added rows  
  38.   
  39. dtCSV.Rows.Add();  
  40.   
  41. int i = 1;  
  42.   
  43. foreach (string cell in row.Split(','))  
  44.   
  45. {  
  46.   
  47. dtCSV.Rows[dtCSV.Rows.Count - 1][i] = cell;  
  48.   
  49. i++;  
  50.   
  51. }  
  52.   
  53. }  
  54.   
  55. }  
  56.   
  57. // Database connection string  
  58.   
  59. string consString = ConfigurationManager.ConnectionStrings["GamesConnectionString"].ConnectionString;  
  60.   
  61. using (SqlConnection con = new SqlConnection(consString))  
  62.   
  63. {  
  64.   
  65. // class use to bulk load data from another source  
  66.   
  67. using (SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(con))  
  68.   
  69. {  
  70.   
  71. // Set the database table name in which data to be added  
  72.   
  73. sqlBulkCopy.DestinationTableName = "dbo.StudentCourses";  
  74.   
  75. con.Open();  
  76.   
  77. // copy all the rows from dataTable to the destination Database table.  
  78.   
  79. sqlBulkCopy.WriteToServer(dtCSV);  
  80.   
  81. con.Close();  
  82.   
  83. lblmessage.Text = "Bulk Data Successfully dump into the Destination table";  
  84.   
  85. lblmessage.ForeColor = System.Drawing.Color.Green;  
  86.   
  87. }  
  88.   
  89. }  
  90.   
  91. }  
  92.   
  93. else  
  94.   
  95. {  
  96.   
  97. lblmessage.Text = "Please upload valid .csv extesnion file";  
  98.   
  99. lblmessage.ForeColor = System.Drawing.Color.Red;  
  100.   
  101. }  
  102.   
  103.   
  104. }   

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.


Read more articles on C#: