rickyah / ini-parser

Read/Write an INI file the easy way!
MIT License
971 stars 241 forks source link

How to specify the name of a known section? #186

Closed Vitokhv closed 5 years ago

Vitokhv commented 5 years ago

The contents of the config.ini file look like this:

[GUID]
value01={c3e342de-91d0-483f-9e89-0d41c0eac2ea}
value02={84a8ca81-482d-4cfb-a2a1-894aa3109e15}
value03={232ca175-6574-4569-9d75-264caa79d56f}

[SETTING]
value01=true
value02=true
value03=false

The code below reads all sections, need to read only in the necessary known section [GUID]

var parser = new FileIniDataParser();
IniData data = parser.ReadFile("C:\\config.ini");         

foreach (SectionData section in data.Sections)
{
       foreach (KeyData key in section.Keys)
        listBox1.Items.Add(key.KeyName);
}

How to specify the desired section in the code? Version ini-parser 2.5.2

zetroot commented 5 years ago

Do you mean, you wnat to read the exact section, without reading and parsing the whole INI file? It seems to me there is no such possibility. If you need only to switch wether you need to do some stuff with the section or not - just use "if" for the inner "foreach" in your example. Something like this

var parser = new FileIniDataParser();
IniData data = parser.ReadFile("C:\\config.ini");         

foreach (SectionData section in data.Sections)
{
       if (section.SectionName == "GUID")
                {
                    foreach (KeyData key in section.Keys)
                        ;//do some stuff here
                }
}

Also you can use LINQ, as SectionDataCollection implements IEnumerable<T> interface:

foreach (SectionData section in data.Sections.Where(s => s.SectionName == "GUID"))
{            
    foreach (KeyData key in section.Keys)
    ; //some cool stuff here                
}
rickyah commented 5 years ago

There is a simpler way

// Iterates over each key inside of GUID
foreach(var key in data["GUID"]) {

}
Vitokhv commented 5 years ago

zetroot Thank you for taking the time to my question, it works:

var parser = new FileIniDataParser();
IniData data = parser.ReadFile("C:\\config.ini");

foreach (SectionData section in data.Sections)
{
    if (section.SectionName == "GUID")
    {
         foreach (KeyData key in section.Keys)
             listBox1.Items.Add(key.KeyName);
    }
}

rickyah Thanks for telling library features, it works:

var parser = new FileIniDataParser();
IniData data = parser.ReadFile("C:\\config.ini");

foreach (var key in data["GUID"])
    listBox1.Items.Add(key.KeyName);

One problem when creating a binding to the listBox had to change key.Name to key.KeyName