Search code examples
c#mappercsvhelper

CSVHelper how to map a string to object


I have a string in a variable, rather than in a file.

Can I use the CSVHelper (https://joshclose.github.io/CsvHelper/) to parse the string and map it onto my object?

The code to map a CSV file works:

TextReader reader = new StreamReader("data.csv");
var csvReader = new CsvReader(reader);
var records = csvReader.GetRecords<CarModel>();

How can I change that to map a string to the object:

String carmodels "make,model,year\n\rFord,Escort,1998\n\rHonda,Civic,1994";
TextReader reader = new StreamReader(carmodels);
var csvReader = new CsvReader(reader);
var records = csvReader.GetRecords<CarModel>();

Thanks for any help,

Mark


Solution

  • Assuming the CarModel type is already mapped correctly, you can use a StringReader rather than a StreamReader:

    string carmodels = "make,model,year\n\rFord,Escort,1998\n\rHonda,Civic,1994";
    using (var reader = new StringReader(carmodels))
    using (var csvReader = new CsvReader(reader))
    {
        var records = csvReader.GetRecords<CarModel>();
    }