If you want to read a Windows INI file that looks like this,
;test.inithen you just make a subclass like this,
[Shape]
Width=100
[Name]
First=John
Last=Williams ,
class TestIni : IniFileand then you can use it like this:
{
public TestIni() : base("test.ini") { }
public class ShapeSection
{
public int Width = 10;
}
public readonly ShapeSection Shape = new ShapeSection();
public class NameSection
{
public string First = "";
public string Last = "";
}
public readonly NameSection Name = new NameSection();
} ,
TestIni ini = new TestIni();It's cool because the structure of the subclass mirrors the structure of the INI file it represents, with a member class for each section containing a field or property for each key.
Console.WriteLine("{0}, {1}", ini.Shape.Width, ini.Name.First); .
There are a lot of INI access utility classes out there (thanks to Microsoft not providing any in the Framework), but all the ones I saw used things like dictionaries to look up values by string. I think the reflection approach makes for neater client code.
Potential improvements include the ability to specify alternate names for member data, allowing you to access key or section names that are not valid C# identifiers; and the ability to write out changes to the member data to the INI file.
No comments:
Post a Comment