Upload And Read Csv File in Asp.net Core 8 MVC Using C#.net

How to upload and read csv file data in controller on submit click in asp.net core 8 mvc using c#.net with StreamReader without saving a file copy.
In today's article I will show you a simple tutorial with example for how you can upload a CSV file and read or fetch the CSV file data using StreamReader and convert into list format in asp.net core mvc using c#.net. In this article I have used asp.net core 8 mvc with c#.net. To upload the file in asp.net core mvc I will use input control of file type. 

Now for this article first create a new asp.net core mvc application with c#.net and add a controller class file. In this class file we will define some properties. I will use property list to store the CSV data into List using c#.net.

    public class Employee
    {
        public int EmpId { get; set; }
        public string Name { get; set; }
        public string Address { get; set; }
    }
In above class I have defined three properties of int and string type. Now let's create a CSV file and add some data in it.

CSV File Data in Asp.net Core MVC
Now let's add a controller class file and add a HttpGet Method of return type IActionResult. 
[HttpGet]
public IActionResult Index()
{           
    return View();
}
After creating the HttpGet method in controller class file we will create a view for putting teh controls. Please check the below code.
@{
    ViewData["Title"] = "Home Page";
}
@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { @enctype = "multipart/form-data" }))
{
    <div style="color:darkred"><h1>Upload CSV File & Read Data</h1></div>
    <div style="font-weight:bold;">Select File:</div>
    <div>
        <input type="file" class="form-control" name="file" />
    </div><br />
    <div><input type="submit" value="Upload CSV File" /></div>
}
In above code to define the form tag I have taken Html.BeginForm. In Html.BeginForm i have passed the Controller, Action and FormMethod type as Post. Here to upload a file in asp.net core mvc we need to add the new { @enctype = "multipart/form-data" }) attribute. Otherwise, we will not get the upload file detail at controller end. 

After defining the form tag i have input control of file type and a input control of submit type. Now lets write code for HttpPost method for getting the uploaded file at controller end and read the CSV data in the List object.
[HttpPost]
public IActionResult Index(IFormFile file)
{
    List<Employee> employee = new List<Employee>();
    List<string> csvStringData = new List<string>();
    StreamReader streamReader = new StreamReader(file.OpenReadStream());
    bool firstRow = true;
    while (streamReader.Peek() >= 0)
    {
        csvStringData.Add(streamReader.ReadLine());
    }
    var tempList = csvStringData.Select(m => m.Split(',')).ToList();
    foreach (var item in tempList)
    {
        if (!firstRow)
        {
            employee.Add(new Employee { EmpId = Convert.ToInt32(item[0]), Name = item[1], Address = item[2] });
        }
        firstRow = false;
    }
    return View();
}
In above code I have passed the IFormFile as parameter to the IActionResult to capture the uploaded file in controller post method. After that I have created the object for Employee List and a list of string type to store the CSV date as a temp list. 

Here I have not saved the uploaded file in the any folder. Instead of making a copy I have used StreamReader to read the uploaded CSV file data. Here I have used OpenReadStream. Now check the below piece of code. 
    while (streamReader.Peek() >= 0)
    {
        csvStringData.Add(streamReader.ReadLine());
    }
In above code I have used while look to read the streamReader data. Here in while look I have used Peek method. In this I have added the value to the list of string type. 
Peek Method in C#.Net! Peek() return the next available character but does not consume it from StreamReade object.
After this I have used Select method with split list string with the help of lambada expression to split the list of string type with comma. You can pass your split character. After splitting the list of string, I have used foreach loop to get the value in the employee list. Here I am skipping the first as it is the header of the CSV file. 
var tempList = csvStringData.Select(m => m.Split(',')).ToList();
    foreach (var item in tempList)
    {
        if (!firstRow)
        {
            employee.Add(new Employee { EmpId = Convert.ToInt32(item[0]), Name = item[1], Address = item[2] });
        }
        firstRow = false;
    }
Now let's run the code to check the output.

Upload CSV file In Asp.Net Core MVC Using C#.Net

Above image shows the selected CSV file and now click on Submit button. Ones we click on Submit button controller Post method break point will execute and here we can see the selected CSV file detail.

Uploaded CSV file Detail in Controller

Here in controller POST method, I have used StreamReader to read the CSV file data. Here we are not saving the file. After reading the file i have used Peak to read the StreamReader  data.

CSV File List Data in List od String

After this I have used Select method to make the collection. 

CSV File in List in Asp.net Core Usig C#.Net
Here in above image, we are getting the CSV data detail in the Employee List. Now we have done let's check the output. Please check the CSV data in the IEnumerable Visualizer.

Upload And Read Csv File in Asp.net Core MVC Using C#.net
upload-and-read-csv-file-in-asp-net-core-mvc-using-c-net.zip 3.6MB

Post a Comment