Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CsvHelper: An element with the same key '' already exists in the ExpandoObject

Tags:

c#

csv

csvhelper

With code similar to, I receive the exception:

An element with the same key '' already exists in the ExpandoObject

using (var reader = new StreamReader("SampleData.csv"))
using (var csv = new CsvReader(reader))
{
    var records = csv.GetRecords<dynamic>();
}
like image 713
Alex KeySmith Avatar asked Nov 02 '25 05:11

Alex KeySmith


1 Answers

This is simply due to CsvHelper is using the column headers by default as the name of the dynamic object's properties:

It is important to ensure csvReaderConfig.HasHeaderRecord = false; is set or to use another technique such as mapping to a class.

var csvReaderConfig = new Configuration();

csvReaderConfig.HasHeaderRecord = false;

using (var reader = new StreamReader("SampleData.csv"))
using (var csv = new CsvReader(reader, csvReaderConfig))
{
    var records = csv.GetRecords<dynamic>();
}
like image 185
Alex KeySmith Avatar answered Nov 03 '25 22:11

Alex KeySmith



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!