I just started to use CSVHelper and it looks very promising. However, I cannot figure out how to best go about enums that are apparently not serialized out of the box.
I have many classes like below. They all contain different enums that ideally would be serialized using the names.
[DataContract(IsReference = true)]
public class Setting1 : LibraryComponent
{
[DataMember]
public InfiltrationModel InfiltrationModel = InfiltrationModel.Constant;
[DataMember]
public double InfiltrationAch { get; set; } = 0.1;
}
[DataContract(IsReference = true)]
public class Setting2 : LibraryComponent
{
[DataMember]
public EconomizerItem EconomizerType { get; set; } = EconomizerItem.NoEconomizer;
[DataMember]
public double HeatRecoveryEfficiencyLatent { get; set; } = 0.65;
}
Then I am using templated functions to read and write everything. I am hoping there is a way to keep this generalized so that I do not have to write custom read write routines for every class.
public void writeLibCSV<T>(string fp, List<T> records)
{
using (var sw = new StreamWriter(fp))
{
var csv = new CsvWriter(sw);
csv.WriteRecords(records);
}
}
public List<T> readLibCSV<T>(string fp)
{
var records = new List<T>();
using (var sr = new StreamReader(fp))
{
var csv = new CsvReader(sr);
records = csv.GetRecords<T>().ToList();
}
return records;
}
I then use the read write functions as such in my code:
writeLibCSV<Setting1>(@"C:\Temp\Setting1.csv", lib.Setting1.ToList());
List<Setting1> in = readLibCSV<Setting1>(@"C:\Temp\Setting1.csv");
The CSV file comes out as shown below. The enum fields seem to be ignored.
InfiltrationAch
0.1
I have tried to read write fields manually using csv.WriteField("EconomizerType"); but this is quite cumbersome. Does anyone have a suggestions how I could make CSVHelper output the enums by default? If I am not misreading the changelog on http://joshclose.github.io/CsvHelper/2.x/ CSVHelper should have built in enum converters since version 1.13?