Wednesday, April 9, 2008

Nerd Party

I wrote this C# class for reading INI files on my own time and I think it's cool so I'm posting it up. It uses reflection to populate the fields and properties in a class with values from an INI file.

If you want to read a Windows INI file that looks like this,
;test.ini

[Shape]
Width=100

[Name]
First=John
Last=Williams
,
then you just make a subclass like this,
class TestIni : IniFile
{
   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();
}
,
and then you can use it like this:
TestIni ini = new TestIni();
Console.WriteLine("{0}, {1}", ini.Shape.Width, ini.Name.First);
.
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.

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: