5

I'm trying to write data to a CSV-file using CsvHelper. However, I always get the following exception:

CsvHelper.Configuration.ConfigurationException: "Types that inherit IEnumerable cannot be auto mapped. Did you accidentally call GetRecord or WriteRecord which acts on a single record instead of calling GetRecords or WriteRecords which acts on a list of records?"

This is my code (C#):

TextWriter outfile = new StreamWriter("blatest.csv");

List<string> test = new List<string>
{
  "hello",
  "world"
};

CsvWriter csv = new CsvWriter(outfile);
csv.WriteRecords(test);

I would like to write a List<string> or (ideally) a List<Dictionary<string, string>> to CSV. What would be the correct code for this? And how can I set the header row?

Any help is appreciated. I really can't wrap my head around this.

Markus
  • 79
  • 1
  • 8
  • Possible duplicate of [Read all values from CSV into a List using CsvHelper](https://stackoverflow.com/questions/33294738/read-all-values-from-csv-into-a-list-using-csvhelper) – Nisarg Shah Mar 02 '18 at 11:18
  • @Nisarg the other post is about reading files with CsvHelper. My post is about writing files with CsvHelper, so it's not a duplicate. From reading the other post I cannot extract any relevant information for my problem with CsvHelper (I don't want no stupid VBA library) – Markus Mar 02 '18 at 11:39

1 Answers1

3

For the error, it is because string implements IEnumerable (because it is char[]). Generally using WriteRecords you pass in an IEnumerable of custom objects.

You could try another way (Example)

using(var stream = new MemoryStream())
using(var reader = new StreamReader(stream))
using(var writer = new StreamWriter(stream))
using(var csvWriter = new CsvHelper.CsvWriter(writer))
{
    //csvWriter.Configuration.HasHeaderRecord = false;

    foreach( var s in test)
    {
        csvWriter.WriteField(s);
    }

    writer.Flush();
    stream.Position = 0;     
    reader.ReadToEnd(); //dump it where you want           
}
SSD
  • 1,373
  • 2
  • 13
  • 20