Reputation: 643
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
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
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