Using CSVHelper
Parsing files is one of the most common coding operations we perform in software development. Often the goal of parsing a file is to transform it into another format. In this blog post, we parse some CSV data, read the data, and write the data to a CSV file. All of which is pretty easy.
First, we need to create a new console application.
dotnet new console
After we have a console application, we need to parse the CSV file. We have a variety of ways we could do this. We could read the file and manually split on the commas. This would be an approach, but it could be confused by some CSV files. It is better to use a library that specializes in the parsing of CSV data. For this, we will use the CSVHelper NuGet package.
dotnet add package CsvHelper
Now reading the CSV file becomes incredibly easy.
If we want to write out a CSV file, CSVHelper helps with that too.
Reading and writing files is a common coding activity. Often, we are translating from one format to another. Sometimes we read from a CSV (or another format) and inject that CSV data into our database. Sometimes we take data from a database and write it to a CSV file. The simple pattern shown in this example is common across a wide range of uses. And using a library such as CSVHelper makes doing this easier and safer.