CsvHelper – Read CSV files in C# .NET Core
Today in this article we will see how to use CsvHelper – Read CSV files in C# .NET Core. Csvhelper is one of the simple and lightweight and most preferred parsers for CSV Reading and writing purposes.
.NET Core framework supports below easy to use other parsers for CSV file read and write purposes,
Today in this article, we will cover the below aspects,
Getting Started
Let’s create a .NET Core application. To keep simple I have used the .NET Core console application. I have used the .NET Core 3.1 version but the below example works in any .NET Core frameworks.
Install Nuget Package
This package is available through Nuget Manager,
PM> Install-Package CsvHelper
It lets you read, parse, and write the CSV and helps you serialize and deserialize the data into proper objects too.
If the CSV file has a header to be read, then Specify the Header flag as true or false.
Here is the example of how to use CsvParser for reading,
partial class Program
{
static void Main(string[] args)
{
List<Userdetails> result;
string jsonString;
using (TextReader fileReader = File.OpenText("TestData.csv"))
{
var csv = new CsvReader(fileReader);
csv.Configuration.HasHeaderRecord = false;
csv.Read();
result = csv.GetRecords<Userdetails>().ToList();
}
//Csv data as Json string if needed
jsonString = JsonConvert.SerializeObject(result);
foreach (UserDetails details in result)
{
Console.WriteLine(details.Name + " " + details.ID + " " + details.City + " " + details.Country);
}
}
I have used the model entity as below,
public class UserDetails
{
public string ID { get; set; }
public string Name { get; set; }
public string City { get; set; }
public string Country { get; set; }
}
CSV to Objects Conversion
As you can see above the GetRecords() method return result data (CSV column and row details) as Objects.
List<UserDetails> result = csv.GetRecords().ToList();
CSV to JSON Conversion
If you ever need to read a CSV file and return it JSON string in .NET Core then the below one-liner will do that trick.
jsonString = JsonConvert.SerializeObject(result);
You can use System.Text.Json as well for serialization and deserialization.
Here is the output on the console,
Other references :
- CSV Parsing in C# using TinyParser and TextFieldParser
Do you have any comments or ideas or any better suggestions to share?
Please sound off your comments below.
Happy Coding !!
Please bookmark this page and share it with your friends. Please Subscribe to the blog to receive notifications on freshly published(2024) best practices and guidelines for software design and development.