CsvHelper
The NuGET package (CsvHelper) is extremely powerful and incredibly easy to use:
Step 1: Create your .NET object
public class Contact
{
public int ContactId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Address { get; set; }
public string CityStateZipCode { get; set; }
public string PhoneNumber { get; set; }
public DateTime DateOfBirth { get; set; }
public decimal GrossPay { get; set; }
public decimal NetPay { get; set; }
}
Step 2: Get your CSV file
"ContactId","FirstName","LastName","Address","CityStateZipCode","PhoneNumber","DateOfBirth","GrossPay","NetPay"
"1","MICHAEL","SMITH","123 6TH AVE","TACOMA, WA 98406","(360) 337-4443","1/1/1970","125000.00","81250.00"
"2","JUSTIN","THOMAS","123 BAY ST","PORT ORCHARD, WA 98366","(360) 337-4711","1/1/1990","65000.00","42250.00"
"3","JANE","DOE","123 OLD BELFAIR HWY","BELFAIR, WA 98528","(360) 337-4467","1/1/1980","82136.00","53388.40"
"4","WILLIAM","JONES","5501 WERNER RD","BREMERTON, WA 98312","(360) 337-4413","1/1/2000","16384.00","10649.60"
Step 3: Read the CSV into a list of objects
public static List<Contact> GetContacts(string csvFileName)
{
using (TextReader txt = new StreamReader(csvFileName))
{
using (var csv = new CsvReader(txt))
{
var contacts = csv.GetRecords();
return contacts.ToList();
}
}
}
Bonus: It handles dynamic and anonymous types!
// Dynamic
var records = csv.GetRecords<dynamic>();
// Using anonymous type for the class definition
var anonymousTypeDefinition = {
Id = default(int),
Name = string.Empty,
MyClass = new MyClass()
};
var records = csv.GetRecords(anonymousTypeDefinition);