Author image

Weston Walker

I'm a full stack developer 🤓 who's a teacher at heart. I create awesome web applications and want to help you do the same. I release new content a couple times a week.


Subscribe to the newsletter to get updates on new posts, articles, videos, projects.....

How to write a CSV file with .NET Core

A tutorial on writing a class list to a CSV file using ASP.NET Core.

Published Jun 12, 2020

At some point in your career you will find yourself having to write data to a csv file. Luckily in .NET Core, a library called Csv Helper makes short work of this task. This tutorial will be in .NET Core but the implementation in .NET is similar.

Install Csv Helper.

dotnet add package CsvHelper

Add dependencies to your class.

using CsvHelper;
using System.Collections.Generic;
using System.IO;
using System.Globalization;

Create a list of objects. For this example I am using a Payment object.

var payments = new List<Payment>() {
  new Payment { Id = 1, Name = "Jerry Seinfeld", Amount = 10.99m, CreatedDate = DateTime.Now },
  new Payment { Id = 2, Name = "George Costanza", Amount = 98.21m, CreatedDate = DateTime.Now },
  new Payment { Id = 3, Name = "Cosmo Kramer", Amount = 54.37m, CreatedDate = DateTime.Now },

Write the list of objects to a csv file. Pass a string for your output path to the StreamWriter. Csv Writer will auto detect the csv column names based on your Classes property names.

using (var writer = new StreamWriter("/Output/payments.csv"))
using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))

The result in output.csv:

1,10.99,Jerry Seinfeld,06/12/2020 08:40:13
2,98.21,George Costanza,06/12/2020 08:40:13
3,54.37,Cosmo Kramer,06/12/2020 08:40:13

View a project containing a full example of reading and writing to a csv file on my Github.