简体   繁体   中英

C#.NET: Read CSV using % converter

I'm reading a CSV file

Name,Score
Pat,99%
Chris,87%

and would like to discard the percent sign when the file is read through FileHelpers

using FileHelpers;

public class PctConverter : ConverterBase
{
    private NumberFormatInfo nfi = new NumberFormatInfo();

    public PctConverter()
    {
        nfi.PercentSymbol = "%";
    }

    public override object StringToField(string from)
    {
        return decimal.Parse(from, NumberStyles.Percent, nfi);
    }
}

[DelimitedRecord(",")]
[IgnoreFirst]
public class Student
{
    public string Name { get; set; }
    public decimal Score { get; set; }
}

var student_file = "students.csv";
var engine = new FileHelperEngine<Student>();
engine.ErrorManager.ErrorMode = ErrorMode.SaveAndContinue;
List<Student> students = engine.ReadFileAsList(student_file);
ErrorInfo[] readingErrors = engine.ErrorManager.Errors;

But my converter is not quite right. Can you suggest why?

You need to specify the converter on the field you want converted, also your converter didn't work for me so I simplified it a bit:

public class PctConverter : ConverterBase
{
    public override object StringToField(string from)
    {
        return decimal.Parse(from.Replace("%", ""));
    }
}

[DelimitedRecord(",")]
[IgnoreFirst]
public class Student
{
    public string Name { get; set; }

    [FieldConverter(typeof(PctConverter))]
    public decimal Score { get; set; }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM