using System.Globalization;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using CsvHelper.TypeConversion;
using CsvHelper.Configuration;
public static void Main()
var customer1 = CreateCustomer(1);
var customer2 = CreateCustomer(2);
var customers = new List<Customer>{customer1, customer2};
WriteAndReadCustomerToCsvFileWithDefaultMapping(customers);
WriteAndReadCustomerToCsvFileWithCustomMapping(customers);
public static void WriteAndReadCustomerToCsvFileWithDefaultMapping(List<Customer> customers)
var fileName = "customers.csv";
Console.WriteLine("========================");
Console.WriteLine("\nUsing default mapping\n\n");
Console.WriteLine("Writing to CSV\n");
WriteToCsvFile(customers, fileName);
Console.WriteLine("\nFile Contents");
Console.WriteLine("-----------------\n");
string fileContent = File.ReadAllText(fileName);
Console.WriteLine(fileContent);
Console.WriteLine("\nReading from CSV\n");
var customersFromCsv = ReadFromCsvFile(fileName);
var customerObjectsText = JsonSerializer.Serialize(customersFromCsv, new JsonSerializerOptions{ WriteIndented = true });
Console.WriteLine(customerObjectsText);
public static void WriteToCsvFile(List<Customer> customers, string fileName)
using (var streamWriter = new StreamWriter(fileName))
using (var csvWriter = new CsvWriter(streamWriter, CultureInfo.InvariantCulture))
csvWriter.WriteRecords(customers);
public static List<Customer> ReadFromCsvFile(string fileName)
using (var streamReader = new StreamReader(fileName))
using (var csvReader = new CsvReader(streamReader, CultureInfo.InvariantCulture))
var customers = csvReader.GetRecords<Customer>();
return new List<Customer>(customers);
public static Customer CreateCustomer(int index)
var customer = new Customer
FirstName = "FN_" + index,
LastName = "LN_" + index,
Street = "Street_" + index,
State = "State_" + index,
public static void WriteAndReadCustomerToCsvFileWithCustomMapping(List<Customer> customers)
var fileName = "customers2.csv";
Console.WriteLine("\n\n========================");
Console.WriteLine("\nUsing custom mapping\n\n");
Console.WriteLine("Writing to CSV\n");
WriteToCsvFileWithCustomMapping(customers, fileName);
Console.WriteLine("\nFile Contents");
Console.WriteLine("-----------------\n");
string fileContent = File.ReadAllText(fileName);
Console.WriteLine(fileContent);
Console.WriteLine("\nReading from CSV\n");
var customersFromCsv = ReadFromCsvFileWithCustomMapping(fileName);
var customerObjectsText = JsonSerializer.Serialize(customersFromCsv, new JsonSerializerOptions{ WriteIndented = true });
Console.WriteLine(customerObjectsText);
public static void WriteToCsvFileWithCustomMapping(List<Customer> customers, string fileName)
using (var streamWriter = new StreamWriter(fileName))
using (var csvWriter = new CsvWriter(streamWriter, CultureInfo.InvariantCulture))
csvWriter.Configuration.RegisterClassMap<CustomerToCsvMap>();
csvWriter.WriteRecords(customers);
public static List<Customer> ReadFromCsvFileWithCustomMapping(string fileName)
using (var streamReader = new StreamReader(fileName))
using (var csvReader = new CsvReader(streamReader, CultureInfo.InvariantCulture))
csvReader.Configuration.RegisterClassMap<CustomerToCsvMap>();
var customers = csvReader.GetRecords<Customer>();
return new List<Customer>(customers);
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age {get; set;}
public Address Address {get; set;}
public string Street {get; set;}
public string City {get; set;}
public string State {get; set;}
public string Zip {get; set;}
public class CustomerToCsvMap : ClassMap<Customer>
public CustomerToCsvMap()
Map(m => m.FirstName).Index(0);
Map(m => m.LastName).Index(1);
Map(m => m.Age).Index(2);
Map(m => m.Address).Index(3).TypeConverter<AddressCsvConverter>();
public class AddressCsvConverter : DefaultTypeConverter
public override object ConvertFromString(string text, IReaderRow row, MemberMapData memberMapData)
string pattern = @"(?<street>[A-Za-z0-9_\s]+)\,\s(?<city>[A-Za-z0-9_\s]+),\s(?<state>[A-Za-z0-9_\s]+)\s(?<zip>[A-Za-z0-9_\s]+)";
var regex = new Regex(pattern);
if (!regex.IsMatch(text))
var match = regex.Match(text);
var address = new Address
Street = match.Groups["street"].Value,
City = match.Groups["city"].Value,
State = match.Groups["state"].Value,
Zip = match.Groups["zip"].Value
public override string ConvertToString(object value, IWriterRow row, MemberMapData memberMapData)
var address = (Address)value;
return $"{address.Street}, {address.City}, {address.State} {address.Zip}";