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?
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() });
});
}