Dealing with CSV files can sometimes be tricky, especially when the data includes commas within the values. In this blog post, we’ll explore how to handle CSV files in C# using the CSVHelper NuGet package, which simplifies the process and handles complex scenarios gracefully.
Reading a CSV File in C# Manually
Initially, I attempted to read a CSV file manually using basic C# code. The CSV file had a header with several attributes and rows of data. One of the values in the rows contained a comma, which posed a challenge when splitting the data by commas.
Here is the original approach:
1 2 3 4 5 6 7 8 | var lines = File.ReadAllLinesAsync( "Employee.csv" ); foreach ( var line in lines) { foreach ( var item in line.Split( ',' )) { Console.WriteLine(item); } } |
Problem: This approach failed when a column value contained a comma, splitting the value into multiple columns.
Introducing CSVHelper
To address this issue, I turned to the CSVHelper NuGet package. This Nuget package is a powerful library for reading and writing CSV files in C#. It handles complex scenarios, such as values containing commas, with ease.
Installing CSVHelper:
- Open your project in Visual Studio.
- Install the CSVHelper NuGet package using the Package Manager Console
1 | Install-Package CsvHelper |
Reading CSV Files with CSVHelper
To read a CSV file using this Nuget package, you need to define a model that matches the structure of your CSV file. Here’s how you can do it:
Model Definition:
1 2 3 4 5 6 | public record Employee { public string Name { get ; init; } public string Address { get ; init; } public int Age { get ; init; } } |
Reading the CSV File:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | using System.Globalization; using CsvHelper; // Define the path to your CSV file var path = "Employee.csv" ; using var reader = new StreamReader(path); using var csv = new CsvReader(reader, CultureInfo.InvariantCulture); var records = csv.GetRecords<Employee>().ToList(); foreach ( var record in records) { Console.WriteLine($ "{record.Name} - {record.Address} - {record.Age}" ); } |
Handling Column Name Mismatches:
If your CSV file has different column names than your model properties, you can use the Name
attribute to map them:
1 2 3 4 5 6 7 | public record Employee { [Name( "Employee Name" )] public string Name { get ; init; } public string Address { get ; init; } public int Age { get ; init; } } |
Writing CSV Files with CSVHelper
Writing data to a CSV file is just as straightforward with CSVHelper.
Creating a List of Records:
1 2 3 4 5 | var employees = new List<Employee> { new Employee { Name = "John Doe" , Address = "123 Main St, Suite 1" , Age = 30 }, new Employee { Name = "Jane Smith" , Address = "456 Elm St" , Age = 25 } }; |
Writing to a CSV File:
1 2 3 | using var writer = new StreamWriter( "Employee1.csv" ); using var csvWriter = new CsvWriter(writer, CultureInfo.InvariantCulture); csvWriter.WriteRecords(employees); |
Output Handling: This Nuget package automatically handles values containing commas by enclosing them in double quotes.
Conclusion
Using CSVHelper simplifies the process of reading and writing CSV files in C#. It handles edge cases, such as values with commas, effortlessly and provides a clean and efficient API. If you found this guide helpful, please head over to my YouTube channel, give it a thumbs up, and subscribe to our channel for more insights and tutorials. Thank you for reading!
Related Videos from my YouTube Channel: