CsvHelper icon indicating copy to clipboard operation
CsvHelper copied to clipboard

Unable to write from List<string[]> to csv file

Open casualsailo opened this issue 1 year ago • 3 comments

Hi,

I am using CsvHelper 33.0.1

I have a list of string arrays that I want to write to a csv file, but I keep getting an error on csv.WriteRecords() or csv.WriteRecord()

CsvHelper.Configuration.ConfigurationException HResult=0x80131500 Message=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? Source=CsvHelper StackTrace: at CsvHelper.Configuration.ClassMap.AutoMap(CsvContext context) at CsvHelper.CsvContext.AutoMap(Type type) at CsvHelper.CsvWriter.WriteHeader(Type type) at CsvHelper.CsvWriter.WriteHeaderFromTypeT at CsvHelper.CsvWriter.WriteRecords[T](IEnumerable`1 records)

This is an example of what I am doing:

void Main()
{
    var input = new List<string[]>()
    {
        new string[] { "a1", "a2" },
        new string[] { "b1", "b2" },
        new string[] { "c1", "c2" }
    };

    using (var writer = new StreamWriter(outputFile))
    using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
    {
        csv.WriteRecords(input);
    }
}

I've also tried

using (var writer = new StreamWriter(outputFile))
using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
{
    foreach (var row in input)
    {
        csv.WriteRecord(row);
    }
}

Am I using WriteRecord()/WriteRecords() incorrectly? Thanks

casualsailo avatar Nov 17 '24 22:11 casualsailo

CsvHelper is expecting an object with members to map rather than an array of strings. I believe the only way to do it would be to have CsvHelper write out the individual fields. See https://github.com/JoshClose/CsvHelper/issues/765

void Main()
{
  var input = new List<string[]>()
  {
    new string[] { "a1", "a2" },
    new string[] { "b1", "b2" },
    new string[] { "c1", "c2" }
  };
  
  //using (var writer = new StreamWriter(Console.Out))
  using (var csv = new CsvWriter(Console.Out, CultureInfo.InvariantCulture))
  {
    foreach (var row in input)
    {
      foreach (var item in row)
      {
         csv.WriteField(item);
      }
      csv.NextRecord();
    }
  }	
}

AltruCoder avatar Nov 18 '24 03:11 AltruCoder

Thanks!

Contrary to what the name implies, it seems to works with string[], and doesn't require string

using (var writer = new StreamWriter(outputFile))
using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
{
    foreach (var row in input)
    {
        csv.WriteField(row);
    }
}

casualsailo avatar Nov 18 '24 05:11 casualsailo

Good to know! You do still need the csv.NextRecord().

AltruCoder avatar Nov 18 '24 14:11 AltruCoder