CsvHelper helps in reading CSV files. But creating the model and mapper classes can be a bit time consuming. On this page you can generate the classes. Just fill inn the fields below with the header for your CSV file. It will generate the model and a mapper class.
Code sample to use classes generated:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
public List<TModel> ReadCsvFile<TModel, TModelMapper>(string file) where TModelMapper : ClassMap<TModel> { var configuration = new Configuration { IncludePrivateMembers = false, IgnoreBlankLines = true, Delimiter = ";" // You may want to change this }; configuration.RegisterClassMap<TModelMapper>(); using (var csvFile = File.OpenText(file)) { var parser = new CsvHelper.CsvReader(csvFile, configuration); return parser.GetRecords<TModel>().ToList(); } } // Then you read the file like this var customers = ReadCsvFile<CustomerModel, CustomerModelMapper>(@"customers.csv"); |
Name: | ||
Header: | ||
Separator: | ||
Mapping type: | Map model to field position Map model to field names |
C# model and mapper classes: