How to Read and Write CSV Files in C# with CsvHelper
CsvHelper
library simplifies this process, providing a flexible, high-performance solution that can handle various file formats and cultural differences.
Introduction:
In this post, we’ll explore how to easily read and write CSV files using the popular CsvHelper
library in C#. Whether you need to import or export data in CSV format, CsvHelper
provides a powerful and simple API for handling these tasks. We’ll go through step-by-step examples of both reading from and writing to CSV files.
Why CsvHelper?
When dealing with CSV files in C#, manual parsing can quickly become error-prone and difficult to maintain. The CsvHelper
library simplifies this process, providing a flexible, high-performance solution that can handle various file formats and cultural differences.
Prerequisites
Before we get started, make sure you have installed CsvHelper
via NuGet:
You’ll also need to include necessary namespaces in your code:
using CsvHelper;
using System.IO;
using System.Globalization;
Step 1: Defining the User
Class
First, define a simple User
class that matches the structure of the data in your CSV file. In this example, the User
class has four properties: Username
, EmploymentID
, Password
, and Department
.
public class User
{
public string Username { get; set; }
public string EmploymentID { get; set; }
public string Password { get; set; }
public string Department { get; set; }
}
Step 2: Reading Data from a CSV File
To read data from a CSV file, we’ll use the StreamReader
class to open the file and the CsvReader
class from CsvHelper
to parse it. Here’s how you can map the CSV data into a list of User
objects:
public static List<User> ReadUsersFromCsv(string filePath)
{
using (var reader = new StreamReader(filePath))
using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
{
var records = csv.GetRecords<User>().ToList();
return records;
}
}
In this example, we’re using CultureInfo.InvariantCulture
to ensure that the CSV is read consistently, regardless of the region or culture settings of the system. This avoids issues that can arise from different regional number and date formats.
Step 3: Writing Data to a CSV File
Now, let’s write data back to a new CSV file. Here’s how to take a list of User
objects and save them:
public static void WriteUsersToCsv(string filePath, List<User> users)
{
using (var writer = new StreamWriter(filePath))
using (var csvWriter = new CsvWriter(writer, CultureInfo.InvariantCulture))
{
csvWriter.WriteRecords(users);
}
}
This method takes the list of users and writes it to the specified file using CsvWriter
. Again, we use CultureInfo.InvariantCulture
to ensure that the data is written in a consistent format across different systems.
Full Example: Reading and Writing CSV Files
Here’s the full example, demonstrating how to read user data from User.csv
and write it to a new file called OutputUser.csv
.
using CsvHelper;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
public class User
{
public string Username { get; set; }
public string EmploymentID { get; set; }
public string Password { get; set; }
public string Department { get; set; }
}
class Program
{
static void Main()
{
var filePath = "User.csv";
// Reading from CSV
var users = ReadUsersFromCsv(filePath);
Console.WriteLine("Reading from CSV file:");
foreach (var user in users)
{
Console.WriteLine($"Username: {user.Username}\tEmploymentID: {user.EmploymentID}\tPassword: {user.Password}\tDepartment: {user.Department}");
}
// Writing to a new CSV file
var outputFilePath = "OutputUser.csv";
WriteUsersToCsv(outputFilePath, users);
Console.WriteLine($"Data successfully written to {outputFilePath}");
}
public static List<User> ReadUsersFromCsv(string filePath)
{
using (var reader = new StreamReader(filePath))
using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
{
var records = csv.GetRecords<User>().ToList();
return records;
}
}
public static void WriteUsersToCsv(string filePath, List<User> users)
{
using (var writer = new StreamWriter(filePath))
using (var csvWriter = new CsvWriter(writer, CultureInfo.InvariantCulture))
{
csvWriter.WriteRecords(users);
}
}
}
Conclusion
With the CsvHelper
library, reading and writing CSV files in C# becomes a straightforward task. By defining a class and using CsvReader
and CsvWriter
, you can easily map data from a CSV into objects and vice versa. Plus, by using CultureInfo.InvariantCulture
, you ensure that your application can handle CSV files consistently across different regions and systems.
If you have any questions or suggestions, feel free to leave a comment below. Happy coding!