In this tutorial, I'll show you how to parser a csv file in .NET Core using C# Code.

You can use CSVHelper or TinyCSVParser to parser a csv file. Both of them can be installed from Manage Nuget Packages

You can also download it directly from website CSVHelper or TinyCSVParser

You can create a class to map data return from your csv file, your properties should correspond the columns in your csv file.

For Example

class Customer
{
    public string CustomerID { get; set; }
    public string CustomerName { get; set; }
    //etc...
}

To read data from the csv file using the CSVHelper class you can write your code as the following

TextReader reader = new StreamReader("filename.txt");
var csvReader = new CsvReader(reader);
var records = csvReader.GetRecords<Customer>();

You can store your csv file with *.txt or *.csv format, your data in csv file separated by commas

If you want to use the TinyCSVParser to read the csv file, you can map your data manual. Because the Tiny CSV doesn’t have auto-mappings

You can create a class to map data return from the csv file as shown below

class CsvCustomerMapping : CsvMapping<Customer>
{
    public CsvCustomerMapping() : base()
    {
        MapProperty(0, x => x.CustomerID);
        MapProperty(1, x => x.CustomerName);
    }
}

The code to actually parse the file

CsvParserOptions csv = new CsvParserOptions(true, ',');
var csvParser = new CsvParser<Customer>(csv, new CsvCustomerMapping());
var records = csvParser.ReadFromFile("filename.txt", Encoding.UTF8);

When comparing benchmarks between TinyCsvParser and CSVHelper, you can see that TinyCsvParser is faster than CSVHelper.