Handling CSV Files in ASP.NET Core Web APIs
Tags: aspnetcore, csharp, dotnet, webdev
Published: 2022-11-02 14:00:14

---
title: Handling CSV Files in ASP.NET Core Web APIs
published: true
date: 2022-11-02 10:40:14 UTC
tags: aspnetcore, csharp, dotnet, webdev
canonical_url: https://www.syncfusion.com/blogs/post/handling-csv-files-in-asp-net-core-web-apis.aspx
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tkmwxy30sft7tq0ygb4v.png
---

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:

- [Visual Studio 2022](https://visualstudio.microsoft.com/vs/ "Visual Studio 2022")
- [.NET SDK 6.0](https://dotnet.microsoft.com/en-us/download/dotnet/6.0 ".NET SDK 6.0")

## What is CSVHelper?

[CSVHelper](https://joshclose.github.io/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](https://www.syncfusion.com/blogs/wp-content/uploads/2022/10/Creating-the-ASP.NET-Core-Web-API-application-1.png)

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](https://www.syncfusion.com/blogs/wp-content/uploads/2022/10/Selecting-.NET-6-framework-for-the-project.png)

## 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](https://www.syncfusion.com/blogs/wp-content/uploads/2022/10/Installing-the-CSVHelper-package.png) 
 
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](https://www.syncfusion.com/blogs/wp-content/uploads/2022/10/Navigating-to-the-Browse-tab-in-the-NuGet-section.png)

Now, create a model class named **Employee**. This class is used to read and write CSV files.

```csharp
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.

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

Create a class named CSVService, inherited from ICSVService.

```csharp
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](https://docs.microsoft.com/en-us/dotnet/api/system.io.streamreader?view=net-6.0 "StreamReader Class") 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.

```csharp
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**.

```csharp
[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](https://www.syncfusion.com/blogs/wp-content/uploads/2022/10/Reading-CSV-files-using-CSVHelper.png)
 
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](https://www.syncfusion.com/blogs/wp-content/uploads/2022/10/Running-the-read-employees-csv-endpoint-to-read-the-CSV.png)

Here we have attached the CSV file we use to run the read.

![Attach the CSV file](https://www.syncfusion.com/blogs/wp-content/uploads/2022/10/Attaching-the-CSV-file-we-used-to-run-the-read..png)

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.

```csharp
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.

```csharp
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](https://docs.microsoft.com/en-us/dotnet/api/system.io.streamwriter?view=net-6.0 "StreamWriter Class") 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.

```csharp
[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](https://www.syncfusion.com/blogs/wp-content/uploads/2022/10/Writing-CSV-files-using-CSVHelper.png)

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](https://www.syncfusion.com/blogs/wp-content/uploads/2022/10/Output-of-the-created-CSV-file-in-the-directory-path-1.png)

## 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](https://www.syncfusion.com/aspnet-core-ui-controls "ASP.NET Core UI Controls") library, powered by [Essential JS 2](https://www.syncfusion.com/javascript-ui-controls "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](https://www.syncfusion.com/account/downloads/studio/ "License and download page of Essential Studio"). If not, you can download a free [30-day trial ](https://www.syncfusion.com/downloads "Free evaluation of the Syncfusion Essential Studio")to evaluate our products.

You can contact us through our [support forum](https://www.syncfusion.com/forums "Syncfusion support forum"), [support portal](https://support.syncfusion.com/ "Syncfusion support portal"), or [feedback portal](https://www.syncfusion.com/feedback/ "Syncfusion feedback portal"). As always, we are happy to assist you!

## Related blogs

- [Syncfusion Essential Studio 2022 Volume 3 Is Here!](https://www.syncfusion.com/blogs/post/syncfusion-essential-studio-2022-volume-3-is-here.aspx "Blog: Syncfusion Essential Studio 2022 Volume 3 Is Here!")
- [Simple Steps to Integrate a Blazor WebAssembly Project with an Existing ASP.NET Core Application](https://www.syncfusion.com/blogs/post/integrate-blazor-webassembly-in-asp-net-core-application.aspx "Blog: Simple Steps to Integrate a Blazor WebAssembly Project with an Existing ASP.NET Core Application")
- [Creating an ASP.NET Core CRUD Web API with Dapper and PostgreSQL](https://www.syncfusion.com/blogs/post/creating-an-asp-net-core-crud-web-api-with-dapper-and-postgresql.aspx "Blog: Creating an ASP.NET Core CRUD Web API with Dapper and PostgreSQL")
- [How to Integrate BoldSign into Your ASP.NET Core Application](https://www.syncfusion.com/blogs/post/integrate-boldsign-into-your-asp-net-core-application.aspx "Blog: How to Integrate BoldSign into Your ASP.NET Core Application")