简体   繁体   中英

CSV to C# FileHelpers

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?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM