In this article I will explain with an example, how to import (insert) CSV file (Text File) data into Database using SqlBulkCopy in ASP.Net MVC Razor.
The uploaded CSV file (Text File) data will be read using File class and the read data will be inserted into SQL Server database using SqlBulkCopy.
SqlBulkCopy class as the name suggests does bulk insert from one source to another and hence all rows from the DataTable can be easily read and inserted using the SqlBulkCopy class.
Note: For beginners in ASP.Net MVC, please refer my article ASP.Net MVC Hello World Tutorial with Sample Program example.
 
 
Database
I have made use of the following table Customers with the schema as follows. CustomerId is an Auto-Increment (Identity) column.
Import (Insert) CSV file (Text file) data into Database using SqlBulkCopy in ASP.Net MVC
 
Note: You can download the database table SQL by clicking the download link below.
          Download SQL file
 
 
Namespaces
You will need to import the following namespaces.
using System.IO;
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
 
 
Controller
The Controller consists of two Action methods.
Action method for handling GET operation
Inside this Action method, simply the View is returned.
 
Action method for handling POST operation for uploading and reading CSV file
This Action method gets called when the CSV file is selected and the Import Button is clicked, and it gets the uploaded file in the HttpPostedFileBase parameter.
Note: In case the HttpPostedFileBase parameter is appearing NULL, then please refer the article, ASP.Net MVC: HttpPostedFileBase always returns NULL.
 
The uploaded CSV file is saved to a folder named Uploads.
The CSV file data is read into a String variable using the File class ReadAllText method.
The CSV file data is split using New Line (\n) and Comma (,) characters and using a loop the data is copied to a DataTable.
Now a connection is established with the database and the SqlBulkCopy object is initialized and I have specified the name of the Table using the DestinationTableName property.
Finally the columns are mapped and all the rows from the DataTable are inserted into the SQL Server table.
Note: The mapping of columns of the DataTable and the SQL Server table is optional and you need to do only in case where your DataTable and/or the SQL Server Table do not have same number of columns or the names of columns are different.
 
public class HomeController : Controller
{
    // GET: Home
    public ActionResult Index()
    {
        return View();
    }
 
    [HttpPost]
    public ActionResult Index(HttpPostedFileBase postedFile)
    {
        string filePath = string.Empty;
        if (postedFile != null)
        {
            string path = Server.MapPath("~/Uploads/");
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
 
            filePath = path + Path.GetFileName(postedFile.FileName);
            string extension = Path.GetExtension(postedFile.FileName);
            postedFile.SaveAs(filePath);
 
            //Create a DataTable.
            DataTable dt = new DataTable();
            dt.Columns.AddRange(new DataColumn[3] { new DataColumn("Id", typeof(int)),
                                new DataColumn("Name", typeof(string)),
                                new DataColumn("Country",typeof(string)) });
 
 
            //Read the contents of CSV file.
            string csvData = System.IO.File.ReadAllText(filePath);
 
            //Execute a loop over the rows.
            foreach (string row in csvData.Split('\n'))
            {
                if (!string.IsNullOrEmpty(row))
                {
                    dt.Rows.Add();
                    int i = 0;
 
                    //Execute a loop over the columns.
                    foreach (string cell in row.Split(','))
                    {
                        dt.Rows[dt.Rows.Count - 1][i] = cell;
                        i++;
                    }
                }
            }
 
            string conString = ConfigurationManager.ConnectionStrings["Constring"].ConnectionString;
            using (SqlConnection con = new SqlConnection(conString))
            {
                using (SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(con))
                {
                    //Set the database table name.
                    sqlBulkCopy.DestinationTableName = "dbo.Customers";
 
                   //[OPTIONAL]: Map the DataTable columns with that of the database table
                    sqlBulkCopy.ColumnMappings.Add("Id", "CustomerId");
                    sqlBulkCopy.ColumnMappings.Add("Name", "Name");
                    sqlBulkCopy.ColumnMappings.Add("Country", "Country");
 
                    con.Open();
                    sqlBulkCopy.WriteToServer(dt);
                    con.Close();
                }
            }
        }
 
        return View();
    }
}
 
 
View
The View consists of an HTML FileUpload element and a Submit Button enclosed in a Form element.
The HTML Form has been created using the Html.BeginForm method which accepts the following parameters.
ActionNameName of the Action. In this case the name is Index.
ControllerName – Name of the Controller. In this case the name is Home.
FormMethod – It specifies the Form Method i.e. GET or POST. In this case it will be set to POST.
HtmlAttributes – This array allows to specify the additional Form Attributes. Here we need to specify enctype = “multipart/form-data” which is necessary for uploading Files.
@{
    Layout = null;
}
 
<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width"/>
    <title>Index</title>
</head>
<body>
    @using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
    {
        <input type="file" name="postedFile"/>
        <input type="submit" value="Import"/>
    }
</body>
</html>
 
 
Screenshots
The CSV File
Import (Insert) CSV file (Text file) data into Database using SqlBulkCopy in ASP.Net MVC
 
Table containing the data from the CSV file
Import (Insert) CSV file (Text file) data into Database using SqlBulkCopy in ASP.Net MVC
 
 
Downloads