Home > Mobile >  More than one method 'ConvertFromString' on type '' is compatible with the suppl
More than one method 'ConvertFromString' on type '' is compatible with the suppl

Time:11-24

My CsvBool converter is

public class CsvBool : BooleanConverter
    {
        public override string ConvertToString(object value, IWriterRow row, MemberMapData memberMapData)
        {
            if (value == null)
                return string.Empty;
            
            var boolValue = (bool)value;

            return boolValue ? "YES" : "NO";
        }

        public override string ConvertFromString(string text, IReaderRow row, MemberMapData memberMapData)
        {
            if (text == null)
                return string.Empty;

            if (text == "YES")
                return "true";
            else
                return "false";   
        }
    }

When writing the file, everything works as expected. All true booleans are written as YES

While trying to read the csv file, i get the error

More than one method 'ConvertFromString' on type 'CsvBool' is compatible with the supplied arguments.

The error is type of CsvHelperException within the first loop

What am i doing wrong here?

using (var reader = new StreamReader(filePath))
   using (var csv = new CsvReader(reader, csvConfig))

     csv.Context.TypeConverterCache.RemoveConverter<bool>();
     csv.Context.TypeConverterCache.AddConverter<bool>(new CsvBool());

     csv.Context.RegisterClassMap<CsvProduct>();
     var CsvProducts = csv.GetRecords<Product>();
     foreach (var CsvProduct in CsvProducts)
     {

     }

and here is my mapping class

public class CsvProduct : ClassMap<Product>
    {
        public CsvProduct()
        {
            Map(m => m.Active).Name("ActiveColumn").TypeConverter<CsvBool>();
        }
    }

CodePudding user response:

Your ConvertFromString needs to return an object instead of string. Since you marked it as return string, it now sees both the original ConvertFromString from the BooleanConverter which returns an object and your ConvertFromString which returns a string.

public override object ConvertFromString(string text, IReaderRow row, MemberMapData memberMapData)
{
    if (text == null)
        return string.Empty;

    if (text == "YES")
        return true;
    else
        return false;
}

FYI, there is already a TypeConverterOption that will do what you are looking for.

Your can either set it individually on the ClassMap

Map(m => m.Active).Name("ActiveColumn").TypeConverterOption.BooleanValues(true,false,"YES").TypeConverterOption.BooleanValues(false,false,"NO");

Or globally on the TypeConverterOptionsCache

csv.Context.TypeConverterOptionsCache.GetOptions<bool>().BooleanTrueValues.Add("YES");
csv.Context.TypeConverterOptionsCache.GetOptions<bool>().BooleanFalseValues.Add("NO");
  • Related