In this article I will explain with an example, how to import CSV File to Database in ASP Net Core (.Net Core 8) MVC.
Note: For beginners in ASP.Net Core (.Net Core 8) MVC, please refer my article ASP.Net Core 8: Hello World Tutorial with Sample Program example.
 
 

Database

I have made use of the following table Customers with the schema as follows.
ASP.Net Core: Import CSV File to Database
 
Note: You can download the database table SQL by clicking the download link below.
          Download SQL file
 
 

Controller

Inside the Controller, first the private properties of IWebHostEnvironment and IConfiguration interface are created.
Then, the interfaces are injected into the Constructor (HomeController) using Dependency Injection method and the injected object are assigned to private properties (created earlier).
 
The Controller consists of following Action methods.

Action method for handling GET operation

Inside this Action method, simply the View is returned.
 

Action method for handling Post operation

This Action method gets called when the CSV file is selected and the Upload Button is clicked.
The uploaded CSV file is received in the IFormFile parameter
Note: The name of the IFormFile parameter and the name of HTML FileUpload element must be exact same, otherwise the IFormFile parameter will be NULL.
 
Inside this Action method, first, the path of the Folder (Directory) where uploaded file will be saved is fetched using IWebHostEnvironment interface and a check is performed whether Directory (Folder) exists if not, then the Directory (Folder) is created inside the wwwroot.
Note: For more details on how to use IWebHostEnvironment in ASP.Net Core, please refer my article Using IWebHostEnvironment in ASP.Net Core.
 
Then, the uploaded CSV file is saved to a folder named Uploads
Note: For more details on how to upload file in ASP.Net Core, please refer my article Upload file in ASP.Net Core.
 
Next, the contents of CSV file is read into a String variable using ReadAllText method of File class and the CSV file data is split using New Line (\n) and Comma (,) characters and using a loop the data is copied to a DataTable
Then, the Connection string is read from AppSettings.json file into a String variable.
Note: For more details about reading Connection String from AppSettings.json, please refer .Net Core 8: Read Connection String from AppSettings.json file.
 
Now the connection is established with the database and the SqlBulkCopy object is initialized and the name of the Table is specified using the DestinationTableName property.
Note: For more details on using ADO.Net in .Net Core, please refer Using ADO.Net in .Net Core 8.0.
 
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
{
    private IWebHostEnvironment Environment;
    private IConfiguration Configuration;
 
    public HomeController(IWebHostEnvironment  _environment,IConfiguration _configuration)
    {
        this.Environment = _environment;
        this.Configuration = _configuration;
    }
 
    // GET: Home
    public IActionResult Index()
    {
        return View();
    }
 
    [HttpPost]
    public IActionResult Index(IFormFile postedFile)
    {
        string path = Path.Combine(this.Environment.WebRootPath,"Uploads");
        if (!Directory.Exists(path))
        {
            Directory.CreateDirectory(path);
        }
 
        string fileName = Path.GetFileName(postedFile.FileName);
        string filePath = Path.Combine(path, fileName);
        using (FileStream stream = new FileStream(filePath, FileMode.Create))
        {
            postedFile.CopyTo(stream);
        }
 
        //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 = this.Configuration.GetSection("ConnectionStrings")["ConString"];
        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

HTML Markup

The View consists of an HTML Form created with following ASP.Net Tag Helper attributes.
asp-action – Name of the Action. In this case the name is Index.
asp-controller – Name of the Controller. In this case the name is Home.
method – It specifies the Form Method i.e. GET or POST. In this case it will be set to POST.
The HTML Form has been assigned with enctype = “multipart/form-data” which is necessary for uploading file.
Inside the HTML Form, there is an HTML FileUpload element and a Submit.
@{
     Layout = null;
}
 
<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <form method="post" enctype="multipart/form-data" asp-controller="Home" asp-action="Index">
        <input type="file" name="postedFile" />
        <input type="submit" value="Upload" />
    </form>
</body>
</html>
 
 

Screenshots

The CSV File

ASP.Net Core: Import CSV File to Database
 

Table containing the data from the CSV file

ASP.Net Core: Import CSV File to Database
 
 

Downloads