.Net CSVHelper访问所有记录

时间:2019-03-13 09:57:59

标签: c# csvhelper

我对如何访问所有记录有些困惑。它不会让我在所有项目上运行foreach(),而只会将第一个作为对象返回。我知道它在文档中说了这一点。但是我不确定该怎么办。

The GetRecords<T> method will return an IEnumerable<T> that will yield 
records. What this means is that only a single record is returned at a time 
as you iterate the records. That also means that only a small portion of the 
file is read into memory. Be careful though. If you do anything that 
executes a LINQ projection, such as calling .ToList(), the entire file will 
be read into memory. CsvReader is forward only, so if you want to run any 
LINQ queries against your data, you'll have to pull the whole file into 
memory. Just know that is what you're doing.

这是我的代码

protected void WatcherCreated(object sender, FileSystemEventArgs e)
    {

        Console.WriteLine("Watcher Created");
        string[] files = Directory.GetFiles(_watchedFolder, "*.csv");
        foreach (string file in files)
        {
            using (var reader = new StreamReader(file))
            using (var csv = new CsvReader(reader))
            {
                try
                {
                    csv.Read();
                    var records = csv.GetRecord<InputCsv>();


                }
                catch (CsvHelper.HeaderValidationException exception)
                {
                    Console.WriteLine(exception);
                    throw;
                }




            }
        }
    }

记录是所谓的IEnumerable。.我最终希望使用该对象或使用Newtonsoft.Json将其解析为json

在csv.GetRecords()之后,甚至没有提供.ToList()选项。

1 个答案:

答案 0 :(得分:1)

函数调用中缺少字母:

__kwdefaults__

您应该拨打var records = csv.GetRecord<InputCsv>(); -注意额外的s。

GetRecords