I'm using CsvHelper to serialize a class to csv file - until here everything works well.
Now I'm trying to find a way to convert the class's enum properties to their int value in the csv, so I could use the CSV for bulk insert later.
I found out the EnumConverter class in CsvHelper but I can't figure out how to properly use it, as all my tries are failing.
Here is my mapping class code
public sealed class MyMapping : CsvClassMap<TradingCalendarException>
{
public MyMapping()
{
EnumConverter enumConverter = new EnumConverter(typeof(CalendarExceptionEntityType));
Map(m => m.ExceptionEntityType).Index(0).Name("EXCEPTION_ENTITY_TYPE").TypeConverter(enumConverter);
Map(m => m.ExceptionEntityIdentifier).Index(1).Name("EXCEPTION_ENTITY_IDENTIFIER");
Map(m => m.OptionType).Index(2).Name("OPTION_TYPE");
Map(m => m.StartDatetime).Index(3).Name("EXCEPTION_START_DATETIME");
Map(m => m.EndDatetime).Index(4).Name("EXCEPTION_END_DATETIME");
Map(m => m.DataSourceType).Index(5).Name("DATA_SOURCE_TYPE");
Map(m => m.Description).Index(6).Name("DESCRIPTION");
}
}
and the writing part
using (StreamWriter file = new StreamWriter(filePath, false, Encoding.UTF8))
{
CsvWriter writer = new CsvWriter(file);
MyMapping mapping = new MyMapping();
writer.Configuration.RegisterClassMap(mapping);
writer.WriteRecords(calendarExceptionList);
}
The rest of the mapping (indexing and naming) is working, it's just the EnumConverter that doesn't do any change.
I didn't find any examples online.
Thank you!
This is the solution I made:
and used it as the following:
I used Yarimi's solution, but found it can't read the enum value back from the .csv (can write ok)
my solution is to make the class extend from EnumTypeConverter, not DefaultTypeConverter.
here is the full code
and here is how it's used
Add a
int
property to yourTradingCalendarException
class that casts back and forth to your custom enum,CalendarExceptionEntityType
, like:Use
Map(m => m.ExceptionEntityTypeInt).Index(0).Name("EXCEPTION_ENTITY_TYPE_INT")
instead of your enum converterMap(m => m.ExceptionEntityType).Index(0).Name("EXCEPTION_ENTITY_TYPE").TypeConverter(new MyMapping())
This is how I did it for the latest version of
CSV Helper
which is7.1.1
:Note: the code above is making use of C# 7 new inline out variables.
More info here: How should I convert a string to an enum in C#?
This is how you make use of the custom
EnumConverter
: