Reputation: 514
I have below code, where I am reading the csv file by passing the file path as parameter. the file is a valid csv file and i am able to read and do the necessary operation successfully. But now the requirement has changed and I will now be getting the CSV file contents as parameter instead of file path. I would like to know how can i modify the below method that gives me same result as my below function:
private IEnumerable<Dictionary<string,EntityProperty>> ReadCSV( string path, IEnumerable<TableField> cols )
{
using( TextReader reader = File.OpenText( path ) )
{
var cache = new TypeConverterCache();
cache.AddConverter<float>( new CSVSingleConverter() );
cache.AddConverter<double>( new CSVDoubleConverter() );
var csv = new CsvReader( reader,
new CsvHelper.Configuration.CsvConfiguration( System.Globalization.CultureInfo.InvariantCulture )
{
Delimiter = ";",
HasHeaderRecord = true,
CultureInfo = System.Globalization.CultureInfo.InvariantCulture,
TypeConverterCache = cache
} );
csv.Read();
csv.ReadHeader();
var map = (
from col in cols
from src in col.Sources()
let index = csv.GetFieldIndex( src, isTryGet: true )
where index != -1
select new { col.Name, Index = index, Type = col.DataType }).ToList();
while( csv.Read() )
{
yield return map.ToDictionary(
col => col.Name,
col => EntityProperty.CreateEntityPropertyFromObject( csv.GetField( col.Type, col.Index ) ) );
}
}
}
and my TableField is class with below objects:
public class TableField
{
public string Name { get; set; }
public string Type { get; set; }
....and so on
Upvotes: 0
Views: 449
Reputation: 595
Have not tested it, but this should do the trick. Change the first few lines to look like this:
private IEnumerable<Dictionary<string,EntityProperty>> ReadCSV( string data, IEnumerable<TableField> cols )
{
using( TextReader reader = new StringReader(data) )
Upvotes: 1