I am a bit confused with how to access all of the records. It will not let me run a foreach() through the items and it only returns the first one as an object. I am aware it says this in the documentation. But I am not sure what to do about it.
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.
Here is my code
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;
}
}
}
}
The records is the supposed IEnumerable.. I eventually want to use the object o parse it into json using Newtonsoft.Json
It doesn't even offer me a .ToList() option after the csv.GetRecords();
You have a missing letter on the function call:
var records = csv.GetRecord<InputCsv>();
You should be calling GetRecords
- note the extra s.
var records = csv.GetRecords<InputCsv>();