Reading and Writing CSV with ASP.NET Core

CSV

https://joshclose.github.io/CsvHelper/

is what I use to manage CSV in my ASP.NET Core projects.

How to read CSV

using (var reader = new StreamReader(file.OpenReadStream(), Encoding.GetEncoding("UTF-8")))
using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
{
   var records = csv.GetRecords<{YOUR MODEL HERE}>();

   foreach (var item in records)
   {
       // Do something here.
   }
}

When you prepare your class, you can go by name or where the column is.

public class Foo
{
    [Index(0)]
    public int Id { get; set; }

    [Index(1)]
    public string Name { get; set; }
}
Published: 2022-04-06