5

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

Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
Mark Tait
  • 545
  • 3
  • 12
  • 22
  • 2
    Possible duplicate of [In C#, how can I create a TextReader object from a string (without writing to disk)](https://stackoverflow.com/questions/7837826/in-c-how-can-i-create-a-textreader-object-from-a-string-without-writing-to-di) – Matt.G Mar 22 '19 at 16:18

2 Answers2

13

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>();
}
Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
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/

Stejin
  • 64
  • 4