我有下面的代码,在这里我通过将文件路径作为参数来读取csv文件。该文件是有效的csv文件,我能够读取并成功执行必要的操作。但是现在需求已更改,我现在将CSV文件内容作为参数而不是文件路径。我想知道如何修改下面的方法,使我的结果与下面的函数相同:
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 ) ) );
}
}
}
我的TableField是具有以下对象的类:
public class TableField
{
public string Name { get; set; }
public string Type { get; set; }
....and so on
还没有测试过,但这应该可以解决问题。更改前几行,如下所示:
private IEnumerable<Dictionary<string,EntityProperty>> ReadCSV( string data, IEnumerable<TableField> cols )
{
using( TextReader reader = new StringReader(data) )
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句