C# CSV

By FoxLearn 2/14/2025 3:04:12 AM   70
In C#, you can read and write CSV data using various methods.

CSV (Comma Separated Values) is a widely used data format for importing and exporting data, commonly employed in spreadsheets and databases. Each line in a CSV file represents a data record, and each record consists of one or more fields, which are separated by commas. Although CSV is a straightforward format, there can be variations, such as different delimiters, newline characters, or quoting styles.

How to read and write CSV data using the CsvHelper library?

To begin using CsvHelper, you first need to add the package to your project:

$ dotnet add package CsvHelper

This command will install the CsvHelper package, allowing you to work with CSV files more efficiently in your C# projects.

C# CSV Read Data by Records

In this example, we read a CSV file by records.

employees.csv

FirstName,LastName,Position
John,Doe,Software Engineer
Roger,Roe,Driver
Lucy,Smith,Teacher

We have this employees.csv file.

For example, c# csv read data

using System.Globalization;
using CsvHelper;
using CsvHelper.Configuration;

var csvConfig = new CsvConfiguration(CultureInfo.CurrentCulture)
{
    HasHeaderRecord = false
};

using var streamReader = File.OpenText("employees.csv");
using var csvReader = new CsvReader(streamReader, csvConfig);

string value;

while (csvReader.Read())
{
    for (int i = 0; csvReader.TryGetField<string>(i, out value); i++)
    {
        Console.Write($"{value} ");
    }

    Console.WriteLine();
}

In this example, the Read method advances the reader to the next record, and we read the fields of the record with TryGetField.

Output:

FirstName LastName Position 
John Doe Software Engineer 
Roger Roe Driver 
Lucy Smith Teacher

C# CSV Read Data into Objects

Next, we read the data into objects using GetRecords.

For example, c# csv read data

using System.Globalization;
using CsvHelper;

using var streamReader = File.OpenText("employees.csv");
using var csvReader = new CsvReader(streamReader, CultureInfo.CurrentCulture);

var employees = csvReader.GetRecords<Employee>();

foreach (var employee in employees)
{
    Console.WriteLine(employee);
}

record Employee(string FirstName, string LastName, string Position);

In this example, we define the Employee record and read the records of employees.csv into instances of this class. GetRecords returns an IEnumerable of the specified type.

Output:

Employee { FirstName = John, LastName = Doe, Position = Software Engineer }
Employee { FirstName = Roger, LastName = Roe, Position = Driver }
Employee { FirstName = Lucy, LastName = Smith, Position = Teacher }

C# CSV Configuration for Custom Format

This example shows how to parse a CSV file with semicolon separators and comments.

employees.csv

# this is employees.csv file
John;Doe;Software Engineer
Roger;Roe;Driver
Lucy;Smith;Teacher

For example, c# csv config

using System.Globalization;
using CsvHelper;
using CsvHelper.Configuration; 

var csvConfig = new CsvConfiguration(CultureInfo.CurrentCulture)
{
    HasHeaderRecord = false,
    Comment = '#',
    AllowComments = true,
    Delimiter = ";",
};

using var streamReader = File.OpenText("employees.csv");
using var csvReader = new CsvReader(streamReader, csvConfig);

while (csvReader.Read())
{
    var firstName = csvReader.GetField(0);
    var lastName = csvReader.GetField(1);
    var position = csvReader.GetField(2);

    Console.WriteLine($"{firstName} {lastName} is a {position}");
}

We configure the CSV reader with CsvConfiguration to handle comments, change the delimiter to semicolon, and prevent headers.

Output:

John Doe is a Software Engineer
Roger Roe is a Driver
Lucy Smith is a Teacher

C# CSV Write Data with WriteField

Now, we write employee data to a CSV file manually using WriteField.

For example, c# csv write data

using System.Globalization;
using System.Text;
using CsvHelper;

var employees = new List<Employee>
{
    new ("John", "Doe", "Software Engineer"),
    new ("Roger", "Roe", "Driver"),
    new ("Lucy", "Smith", "Teacher"),
};

using var mem = new MemoryStream();
using var writer = new StreamWriter(mem);
using var csvWriter = new CsvWriter(writer, CultureInfo.CurrentCulture);

csvWriter.WriteField("FirstName");
csvWriter.WriteField("LastName");
csvWriter.WriteField("Position");
csvWriter.NextRecord();

foreach (var employee in employees)
{
    csvWriter.WriteField(employee.FirstName);
    csvWriter.WriteField(employee.LastName);
    csvWriter.WriteField(employee.Position);
    csvWriter.NextRecord();
}

writer.Flush();
var res = Encoding.UTF8.GetString(mem.ToArray());
Console.WriteLine(res);

record Employee(string FirstName, string LastName, string Position);

Here, we write the employee data into memory and print it out.

FirstName,LastName,Position
John,Doe,Software Engineer
Roger,Roe,Driver
Lucy,Smith,Teacher

C# CSV Write Data with WriteRecords

In this example, we write all records at once using WriteRecords.

For example, c# csv write data

using System.Globalization;
using CsvHelper;

var employees = new List<Employee> 
{
    new ("John", "Doe", "Software Engineer"),
    new ("Lucy", "Smith", "Teacher"),
    new ("Roger", "Roe", "Driver"),
};

using var writer = new StreamWriter(Console.OpenStandardOutput());
using var csvWriter = new CsvWriter(writer, CultureInfo.CurrentCulture);

csvWriter.WriteHeader<Employee>();
csvWriter.NextRecord(); // adds new line after header
csvWriter.WriteRecords(employees);

record Employee(string FirstName, string LastName, string Position);

This example writes all employee data in one go with WriteRecords, using the WriteHeader method to include the headers.

Output:

FirstName,LastName,Position
John,Doe,Software Engineer
Lucy,Smith,Teacher
Roger,Roe,Driver

C# Custom CSV Solution with LINQ

Here, we parse a CSV file using LINQ to sort employee data by date of birth.

data.csv

John Doe, Software Engineer, 12/5/1997
Jane Doe, Teacher, 5/10/1983
Robert Smith, Driver, 4/2/2001
Maria Smith, Cook, 9/11/1976

For example, c# custom csv

using System.Text;

var path = "data.csv";
var lines = File.ReadLines(path, Encoding.UTF8);

var employees = from line in lines
                let fields = line.Replace(", ", ",").Split(",")
                select new Employee(fields[0], fields[1], DateTime.Parse(fields[2]));

var sorted = from employee in employees
             orderby employee.DateOfBirth descending
             select employee;

foreach (var employee in sorted)
{
    Console.WriteLine(employee);
}

public record Employee(string Name, string Position, DateTime DateOfBirth);

This example uses LINQ to parse and sort employees by birthdate.

Output:

Employee { Name = Robert Smith, Position = Driver, DateOfBirth = 4/2/2001 12:00:00 AM }
Employee { Name = John Doe, Position = Software Engineer, DateOfBirth = 12/5/1997 12:00:00 AM }
Employee { Name = Jane Doe, Position = Teacher, DateOfBirth = 5/10/1983 12:00:00 AM }
Employee { Name = Maria Smith, Position = Cook, DateOfBirth = 9/11/1976 12:00:00 AM }