How to Read and Write to a CSV File in C#
Working with CSV files in C# can be accomplished through several approaches, with the most straightforward being the built-in File class methods combined with string manipulation.
For basic CSV operations, you can use File.ReadAllLines()
to read the entire file into an array of strings, and File.WriteAllLines()
to write data back to a CSV file.
However, for more robust CSV handling, it's recommended to use a dedicated CSV library like CsvHelper, which properly handles edge cases such as commas within quoted fields, escaped characters, and different cultural formats.
This library provides strongly-typed reading and writing capabilities, making it easier to map CSV data to C# objects.
For optimal performance and memory efficiency when dealing with large CSV files, you should consider using StreamReader
and StreamWriter
classes, which allow you to process the file line by line rather than loading it entirely into memory.
Remember to always properly dispose of these resources using using
statements. When writing CSV data, be mindful of proper escaping and quoting rules – fields containing commas, quotes, or newlines should be enclosed in quotes and any embedded quotes should be doubled.
Example
// Basic CSV reading
string[] lines = File.ReadAllLines("data.csv");
foreach (string line in lines)
{
string[] values = line.Split(',');
// Process values
}
// Basic CSV writing
var data = new List<string[]>
{
new[] { "Name", "Age", "City" },
new[] { "John Doe", "30", "New York" }
};
File.WriteAllLines("output.csv", data.Select(line => string.Join(",", line)));
// Using StreamReader for large files
using (var reader = new StreamReader("data.csv"))
{
while (!reader.EndOfStream)
{
string line = reader.ReadLine();
// Process line
}
}
// Using CsvHelper (requires NuGet package)
using (var reader = new StreamReader("data.csv"))
using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
{
var records = csv.GetRecords<MyClass>().ToList();
}