Mark Tait
Mark Tait

Reputation: 643

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

Upvotes: 6

Views: 11680

Answers (2)

Joel Coehoorn
Joel Coehoorn

Reputation: 416179

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>();
}

Upvotes: 15

Stejin
Stejin

Reputation: 64

You "need" to setup a mapping for your class, so it know's which column goes to which property. Even the .AutoMap() can work for you. https://joshclose.github.io/CsvHelper/examples/configuration/class-maps/auto-mapping/

Upvotes: 0

Related Questions