Reputation: 2965
I want to use FileHelpers
to read an extremely basic CSV
file into C#.
I have a Model
that looks like this;
[DelimitedRecord(",")]
[IgnoreFirst()]
public class NavigationButton
{
public int ID;
public string Text;
public string Path;
}
The CSV
file looks like this;
I want to be able to read the appropriate lines and create a new NavigationButton
for each record read in from the CSV
file. I have read them into a DataTable
using;
public DataTable GetNavigationButtonNames()
{
var filename = @"C:\Desktop\NavigationButtons.csv";
var engine = new FileHelperEngine(typeof(NavigationButton));
return engine.ReadFileAsDT(filename);
}
but I now cannot loop through the DataTable
as it doesn't implement IEnumerable
. I would have created a new NavigationButton
in a foreach
loop and added in the appropriate rows, however this cannot be done the way I have started out.
How can I change this method so that I can loop through the object I read into from the CSV
file and create a new button for each row in the CSV
file?
Upvotes: 1
Views: 3661
Reputation: 11326
Use the generic version of FileHelperEngine<T>
instead, then you can do:
var filename = @"C:\Desktop\NavigationButtons.csv";
var engine = new FileHelperEngine<NavigationButton>();
// ReadFile returns an array of NavigationButton
var records = engine.ReadFile(filename);
// then you can do your foreach or just get the button names with LINQ
return records.Select(x => x.Text);
The documentation for ReadFile() is here.
Or there is also ReadFileAsList() if you prefer.
Upvotes: 2
Reputation: 13248
How about this:
List<NavigationButton> buttons = new List<NavigationButton>();
DataTable dt = GetNavigationButtonNames();
foreach (DataRow dr in dt.Rows)
{
buttons.Add(new NavigationButton
{
ID = int.Parse(dr["id"]),
Text = dr["Text"].ToString(),
Path = dr["Path"].ToString() });
});
}
Upvotes: 0