2

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?

timkado
  • 1,922
  • 2
  • 17
  • 27
  • 1
    Is it because InfiltrationModel is a public field rather than a property? Does Setting2 serialize ok? – pmcilreavy Jan 29 '18 at 02:41
  • 1
    This looks like it is nearly a duplicate of https://stackoverflow.com/questions/31666915/how-to-use-enumconverter-with-csvhelper although this differs in that this question asks about how to serialize with the name rather than value. Although probably a very similar answer, that's probably enough different that this shouldn't be closed as dupe. – Jim L Jan 29 '18 at 02:42
  • yup - changing this to a property with { get; set; } did the trick... – timkado Jan 29 '18 at 02:45

0 Answers0