6

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

1

2 Answers 2

16

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>(); } 
Sign up to request clarification or add additional context in comments.

1 Comment

CsvReader(reader, CultureInfo.InvariantCulture) for the new version.
0

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/

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.