Handling CSV Files in ASP.NET Core Web APIs | Syncfusion Blogs
Live Chat Icon For mobile
Live Chat Icon
Popular Categories.NET  (174).NET Core  (29).NET MAUI  (207)Angular  (109)ASP.NET  (51)ASP.NET Core  (82)ASP.NET MVC  (89)Azure  (41)Black Friday Deal  (1)Blazor  (219)BoldSign  (14)DocIO  (24)Essential JS 2  (107)Essential Studio  (200)File Formats  (66)Flutter  (133)JavaScript  (221)Microsoft  (119)PDF  (81)Python  (1)React  (100)Streamlit  (1)Succinctly series  (131)Syncfusion  (917)TypeScript  (33)Uno Platform  (3)UWP  (4)Vue  (45)Webinar  (51)Windows Forms  (61)WinUI  (68)WPF  (159)Xamarin  (161)XlsIO  (36)Other CategoriesBarcode  (5)BI  (29)Bold BI  (8)Bold Reports  (2)Build conference  (8)Business intelligence  (55)Button  (4)C#  (149)Chart  (131)Cloud  (15)Company  (443)Dashboard  (8)Data Science  (3)Data Validation  (8)DataGrid  (63)Development  (631)Doc  (8)DockingManager  (1)eBook  (99)Enterprise  (22)Entity Framework  (5)Essential Tools  (14)Excel  (40)Extensions  (22)File Manager  (7)Gantt  (18)Gauge  (12)Git  (5)Grid  (31)HTML  (13)Installer  (2)Knockout  (2)Language  (1)LINQPad  (1)Linux  (2)M-Commerce  (1)Metro Studio  (11)Mobile  (507)Mobile MVC  (9)OLAP server  (1)Open source  (1)Orubase  (12)Partners  (21)PDF viewer  (43)Performance  (12)PHP  (2)PivotGrid  (4)Predictive Analytics  (6)Report Server  (3)Reporting  (10)Reporting / Back Office  (11)Rich Text Editor  (12)Road Map  (12)Scheduler  (52)Security  (3)SfDataGrid  (9)Silverlight  (21)Sneak Peek  (31)Solution Services  (4)Spreadsheet  (11)SQL  (11)Stock Chart  (1)Surface  (4)Tablets  (5)Theme  (12)Tips and Tricks  (112)UI  (387)Uncategorized  (68)Unix  (2)User interface  (68)Visual State Manager  (2)Visual Studio  (31)Visual Studio Code  (19)Web  (595)What's new  (332)Windows 8  (19)Windows App  (2)Windows Phone  (15)Windows Phone 7  (9)WinRT  (26)
Handling CSV Files in ASP.NET Core Web APIs

Handling CSV Files in ASP.NET Core Web APIs

Handling CSV files can be essential for developers in applications using ASP.NET Core Web APIs. There are many approaches to handling CSV, and CSVHelper is a handy NuGet package for doing so easily. This article will discuss how to handle CSV files using the CSVHelper library in an ASP.NET Core Web API.

Prerequisites

Before creating the application, you need to have the following tools installed:

What is CSVHelper?

CSVHelper is an open-source .NET library for reading and writing CSV files. It is speedy, flexible, and easy to use. We can read and write CSV files using the model class. Also, some configurations can map the model class with the headers of the CSV files, if required.

Creating the ASP.NET Core Web API application

First, create an ASP.NET Core Web API project using Visual Studio 2022. To do so, open Visual Studio and select a new project with an ASP.NET Core Web API template, as in the following figure.

Select ASP.NET Core Web API option
Now, select the .NET 6 framework for this project, like in the next figure. Then, create the project and run it to check if everything is working.Select .NET 6 framework for the project

Installing the CSVHelper package

Then, to install the CSVHelper package in our project, click right on the project and select the Manage NuGet Packages… option, as shown in the figure.

Select the Manage NuGet Packages option
Then, navigate to the Browse tab in the NuGet section, search for the CSVHelper version 28.0.1 package, and install it, like in the following figure.

Navigating to the Browse tab and install the CsvHelper
Now, create a model class named Employee. This class is used to read and write CSV files.

public class Employee
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
    public string City { get; set; }
    public string JobPosition { get; set; }
}

Note: We have created the Employee model class only for demonstration purposes. You can use any model class you need for your project.

Reading CSV files using CSVHelper

Now, we create a service to read CSV files using the CSVHelper NuGet package. For this, create a folder named Services in the root directory. Then, create an interface named ICSVService, similar to the next sample.

public interface ICSVService
{
   public IEnumerable<T> ReadCSV<T>(Stream file);
}

Create a class named CSVService, inherited from ICSVService.

public class CSVService : ICSVService
{
    public IEnumerable<T> ReadCSV<T>(Stream file)
    {
        var reader = new StreamReader(file);
        var csv = new CsvReader(reader, CultureInfo.InvariantCulture);

        var records = csv.GetRecords<T>();
        return records;
    }
}

We have used a method-level generic to deal with the model class. We can use this method with any model class to read CSV files. We have also passed the file stream as a parameter to the ReadCSV method. The StreamReader reads the text and characters from the file stream. Later, we used CsvReader to transfer the content read from StreamReader into the memory. Then, the GetRecords method returned the data of CSV files. We don’t need any configurations if our class property names match the headers of CSV files.

After all this, register the CSV service in the Program.cs, as shown in the next code.

builder.Services.AddScoped<ICSVService, CSVService>();

Next, create a controller class named EmployeeController inside the Controllers folder. Then, create the HttpPost request to read the CSV file using the ICSVService.

[ApiController]
[Route("[controller]")]
public class EmployeeController : Controller
{
   private readonly ICSVService _csvService;

   public EmployeeController(ICSVService csvService)
   {
       _csvService = csvService;
   }

   [HttpPost("read-employees-csv")]
   public async Task<IActionResult> GetEmployeeCSV([FromForm] IFormFileCollection file)
    {
        var employees = _csvService.ReadCSV<Employee>(file[0].OpenReadStream());

        return Ok(employees);
    }
}

We injected the ICSVService to use the read operation for CSV files. Also, EmployeeController uses the ApiController attribute to implement the Web API controller in ASP.NET Core. Then, we used the ReadCSV method of the CSVService to get the data of the CSV file after reading it.

First, let’s run the application. The following is the screenshot of the CSV file we use to read the data.

Reading CSV files using CSVHelper
Then, run the read-employees-csv endpoint to read the CSV file like in the following figure.

Run the read-employees-csv endpoint to read the CSV
Here we have attached the CSV file we use to run the read.

Attach the CSV file
We received a response after running the API successfully.

Writing CSV files using CSVHelper

We use CSVService to create a CSV write method using the CSVHelper. For this, add an abstract method named WriteCSV<T> in the ICSVService interface.

public interface ICSVService
{
    public IEnumerable<T> ReadCSV<T>(Stream file);
    void WriteCSV<T>(List<T> records);
}

After that, implement the WriteCSV method in the CSVService class like in the following code.

public class CSVService : ICSVService
{
    public IEnumerable<T> ReadCSV<T>(Stream file)
    {
        var reader = new StreamReader(file);
        var csv = new CsvReader(reader, CultureInfo.InvariantCulture);

        var records = csv.GetRecords<T>();
        return records;
    }

    public void WriteCSV<T>(List<T> records)
    {
        using (var writer = new StreamWriter("D:\\file.csv"))
        using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
        {
            csv.WriteRecords(records);
        }
    }
}

In the WriteCSV<T> method, the StreamWriter is used to create and write files in the path specified in the parameter. The CsvWriter is used to create the actual CSV files using the StreamWriter instance created. The WriteRecords method writes all the data into the files.

Now, use EmployeeController to create a HttpPost request to create and write the CSV file.

[ApiController]
[Route("[controller]")]
public class EmployeeController : Controller
{
    private readonly ICSVService _csvService;


    public EmployeeController(ICSVService csvService)
    {
        _csvService = csvService;
    }

    [HttpPost("write-employee-csv")]
    public async Task<IActionResult> WriteEmployeeCSV([FromBody] List<Employee> employees)
    {
        _csvService.WriteCSV<Employee>(employees);

        return Ok();
    }

    [HttpPost("read-employees-csv")]
    public async Task<IActionResult> GetEmployeeCSV([FromForm] IFormFileCollection file)
    {
        var employees = _csvService.ReadCSV<Employee>(file[0].OpenReadStream());

        return Ok(employees);
    }
}

We implemented the new HttpPost request to write the CSV files using the WriteCSV<Employee> method of CSVService.

Let’s run the Web API application. Then, we run the write-employee-csv endpoint to test the service.

Run the write-employee-csv endpoint to test the service
We used Swagger to run and test the API to write the CSV. We passed a list with two employee objects.

And so, we have successfully created a CSV file in the directory path. The employee data is in the CSV file, like in the next figure.
Creating CSV file using CsvHelper package

Conclusion

This article discussed handling CSV files using the CSVHelper package with an ASP. NET Core Web API application. This included performing read and write operations in the CSV file using the CSVHelper package.

I hope this article will help you handle your next project’s CSV files. Thank you for reading.

The Syncfusion ASP.NET Core UI control library, powered by Essential JS 2, is the only suite you will ever need to build an app. It contains over 70 high-performance, lightweight, modular, and responsive UI controls in a single package. Use them to build stunning web apps!

If you’re already a Syncfusion user, you can download the product setup. If not, you can download a free 30-day trial to evaluate our products.

You can contact us through our support forumsupport portal, or feedback portal. As always, we are happy to assist you!

Related blogs

Tags:

Share this post:

Comments (1)

Thanks for the article , this is very helpful. Does CSV helper provides any options to validate the file ?How to validate CSV file?

Comments are closed.

Popular Now

Be the first to get updates

Subscribe RSS feed

Be the first to get updates

Subscribe RSS feed