簡體   English   中英

在 C# 中以文本為參數讀取 Csv 文件

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM