using System.Collections;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Collections.ObjectModel;
using CsvHelper.Configuration;
using CsvHelper.Configuration.Attributes;
using CsvHelper.Expressions;
using CsvHelper.TypeConversion;
public int Number { get; set; }
public string Name { get; set; }
public class AccountDtoMap : ClassMap<AccountDto>
Map(m => m.Number).Index(0);
Map(m => m.Name).Index(1);
public static List<T> ReadFile<T>(string file)
var errs = new List<string>();
var cfg = new CsvHelper.Configuration.CsvConfiguration(CultureInfo.InvariantCulture)
MissingFieldFound = (context) => { errs.Add($"{typeof(T)} missing field: {context.Context.Parser.RawRecord}"); },
BadDataFound = (context) => { errs.Add($"{typeof(T)} bad data: {context.RawRecord}"); },
using (var csv = new CsvReader(new StreamReader(file), cfg))
csv.Context.RegisterClassMap<AccountDtoMap>();
var list = csv.GetRecords<T>().ToList();
Console.WriteLine(string.Join("\n", errs));
Assert.AreEqual(0, errs.Count);
public static void Test()
var file = @"question66824728.csv";
Console.WriteLine("Input:");
Console.WriteLine(string.Join("\n", GetCSV()));
File.WriteAllText(file, GetCSV());
var list = ReadFile<AccountDto>(file);
Console.WriteLine("Result:");
Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(list, Newtonsoft.Json.Formatting.Indented));
public static void Main()
Console.WriteLine("Environment version: {0} ({1})", System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription , GetNetCoreVersion());
Console.WriteLine("CsvHelper: " + typeof(CsvHelper.Configuration.CsvConfiguration).Assembly.FullName);
Console.WriteLine("Failed with unhandled exception: ");
public static string GetNetCoreVersion()
var assembly = typeof(System.Runtime.GCSettings).GetTypeInfo().Assembly;
var assemblyPath = assembly.CodeBase.Split(new[] { '/', '\\' }, StringSplitOptions.RemoveEmptyEntries);
int netCoreAppIndex = Array.IndexOf(assemblyPath, "Microsoft.NETCore.App");
if (netCoreAppIndex > 0 && netCoreAppIndex < assemblyPath.Length - 2)
return assemblyPath[netCoreAppIndex + 1];