Search code examples
c#csvhelper

upgrade issues when upgrading CSVhelper libraries from version 2.7 to 30


My application is using CSVHelper libraries of very old version 2.7.1. Now I want to upgrade to the latest version of CSVHelper version 30. I have installed using the NuGet package manager. When I build my application, it throws errors. Below is the old code that throws an error.

 csvReader.Configuration.HasHeaderRecord = hasHeaderRecord;
    csvReader.Configuration.IgnoreBlankLines = false;
    csvReader.Configuration.IgnoreReadingExceptions = true;
    csvReader.Configuration.WillThrowOnMissingField = false;
    csvReader.Configuration.TrimFields = true;
     csvReader.Configuration.ReadingExceptionCallback =
                        (ex, row) =>
                        {
                            if (ex is CsvHelper.TypeConversion.CsvTypeConverterException)
                            {
                                foreach (DictionaryEntry error in ex.Data)
                                {
                                    AddRowError(row.Row, error.Value.ToString() + " Column Name: '" + GetColumnName(row) + "'");
                                }
                            }
                            else if (ex is FormatException)
                            {
                                AddRowError(row.Row, ex.Message + " Column Name: '" + GetColumnName(row) + "' Column Value: '" + GetColumnValue(row) + "'");
                            }
                            else
                            {
                                AddRowError(row.Row, string.Format("Line[{0}]: {1}", row.Row, ex.StackTrace));
                            }

                        };

One more error about The type or namespace name 'ICsvReader' could not be found (are you missing a using directive or an assembly reference?)

Can anyone suggest how to fix these upgradation issues?


Solution

  • Configuration must be passed in to the CsvReader constructor. The constructor also now requires either CultureInfo or IReaderConfiguration to be passed in with the TextReader.

    void Main()
    {
        var config = new CsvConfiguration(CultureInfo.InvariantCulture)
        {
            IgnoreBlankLines = false,
            ReadingExceptionOccurred = args => { Console.WriteLine(args.Exception.ToString()); return false;},
            MissingFieldFound = null,
            TrimOptions = TrimOptions.Trim
        };
        
        using (var reader = new StringReader("Id,Name\n1\n2,name2\nthree,name3\n4,name4"))
        using (var csv = new CsvReader(reader, config))
        {
            var records = csv.GetRecords<Foo>().Dump();
        }
    }
    
    public class Foo
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }