Search code examples
c#.netcsvcsvhelper

How to serialize the right class when there are several with CSVHelper


I would like to know if it is possible to serialize the right class when there are several different with CSVHelper, ex :

There are two classes, A and B, when I load the data from a CSV file(it has been exported from Class A or B), the data will be loaded into either the right class, or A or B...

The solution :

public void ImportFromCSV_V2(ref Buses_Data buses_Data0, string filepath)
        {
            // Ouverture du document 
            using (TextReader fileReader = File.OpenText(filepath))
            {
                var csv = new CsvReader(fileReader);
                csv.Configuration.Delimiter = ";";
                var records = csv.GetRecords<ServiceBusCSV>();
                foreach (var record in records)
                {
                    buses_Data0.ServiceBusCSV_List.Add(record);
                }
            }
        }

Solution

  • I think I would use the factory pattern.
    Load the CSV file, get the header (or understand in some other way what kind on CSV you are loading and what object you have to create), then build the appropriate object using CSVHelper library or similar.
    With some effort you can make the factory abstract and inject at runtime the concrete factory you need to load a particular CSV file.