CsvHelper is .NET library for reading and writing CSV files. Extremely fast, flexible and easy to use. Supports reading and writing of custom class objects.
Simple application
Create a new Console application & install CsvHelper by running the following from the Package Manager Console.
Install-Package CsvHelper
A Person Class
internal class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
Reading function
static void ReadCsvFile(string filename)
{
TextReader textReader = File.OpenText(filename);
var csv = new CsvReader(textReader);
var people = csv.GetRecords<Person>();
foreach (var person in people)
{
Console.WriteLine($"Name {person.Name} age : {person.Age}");
}
textReader.Close();
}
Writing function
static void WriteCsvFile(string filename, IEnumerable<Person> people)
{
TextWriter textWriter = File.CreateText(filename);
var csvWriter = new CsvWriter(textWriter);
csvWriter.WriteRecords(people);
textWriter.Close();
}
Main function
static void Main(string[] args)
{
var filename = Directory.GetCurrentDirectory() + @"\file.csv";
List<Person> list = new List<Person>() {
new Person(){Name= "Ronaldo", Age= 29},
new Person(){Name= "Missi", Age= 28}
};
WriteCsvFile(filename, list);
ReadCsvFile(filename);
Console.ReadLine();
}
NOTE: For more informations , please see CsvHelper.
That’s it see you soon!.