0

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

1 Answer 1

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.