[英]Reading Csv file with text as parameter in C#
我有下面的代码,我在其中通过将文件路径作为参数传递来读取 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) )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.