Search code examples
c#csvhelper

C# CsvWriter throws "CsvWriter does not contain a constructor that takes 1 arguments" after update from 2.8.4 to 27.1.1


I updated the package for CsvHelper in my project from 2.8.4 to 27.1 & it looks like method I had been using has been updated.

It is now taking two more arguments.

I am not sure what CsvConfiguration or CultureInfo is, or what I need to do to correct this error.

CsvWriter does not contain a constructor that takes 1 argument.

The new methods:

public CsvWriter(TextWriter writer, CsvConfiguration configuration);

public CsvWriter(TextWriter writer, CultureInfo culture, bool leaveOpen = false);

My code:

using(var fs = new MemoryStream()) {
  using(var tx = new StreamWriter(fs)) {
    var csv = new CsvWriter(tx);
    csv.WriteHeader<TemplateCsvModel>();
    csv.WriteRecords(templates);
    csv.Dispose();
    return Encoding.UTF8.GetPreamble().Concat(fs.ToArray()).ToArray();
  }
}

Solution

  • CultureInfo is needed to account for different formatting & parsings between various cultures as not everyone in the world formats dates, currency etc. the same.

    If you don't need to parse your data based on the user's local settings, use CultureInfo.InvariantCulture:

    using (var fs = new MemoryStream()) {
        using var tx = new StreamWriter(fs)
        using (var csv = new CsvWriter(tx, CultureInfo.InvariantCulture) {
            csv.WriteHeader<TemplateCsvModel>();
            csv.WriteRecords(templates);
            return Encoding.UTF8.GetPreamble().Concat(fs.ToArray()).ToArray();
          }
    }