[英]Reading Csv file with text as parameter in C#
I have below code, where I am reading the csv file by passing the file path as parameter.我有下面的代码,我在其中通过将文件路径作为参数传递来读取 csv 文件。 the file is a valid csv file and i am able to read and do the necessary operation successfully.该文件是一个有效的 csv 文件,我能够成功读取并执行必要的操作。 But now the requirement has changed and I will now be getting the CSV file contents as parameter instead of file path.但是现在需求已经改变,我现在将获取 CSV 文件内容作为参数而不是文件路径。 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:我的 TableField 是具有以下对象的类:
public class TableField
{
public string Name { get; set; }
public string Type { get; set; }
....and so on
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) )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.