• entries
743
1924
• views
578689

# Reinventing wheels

68 views

Been reinventing the wheel again. Don't shout at me.

I wanted a flexible way to store application settings and I couldn't quite get my head around System.Xml.XmlReader or the dynamic properties stuff so I've come up with the following settings format:

; random example (this is a comment)MainWindow{    Position    {        X=10 ; this is also a comment        Y=20     }    Size    {        Width=100        Height=90    }}Levels{    Level1    Level2    Level3}

You can nest the namespaces as deeply as you want and each item can either be a Name-Value pair or just a Value.

The nice bit is how easy it is to then access this stuff in a C# program. If you know in advance the properties that should be in the file, and it would be an error if they were not, you can just do:

try    {    ConfigStream Cs=new ConfigStream("settings.cfg");    int X=Cs["MainWindow"]["Position"]["X"].AsInt();    int Y=Cs["MainWindow"]["Position"]["Y"].AsInt();    }catch(ConfigStreamException E)    {    ShowMessage(E.Message,"Error",MessageBoxButtons.OK,MessageBoxIcon.Error);    }

Alternatively, to programmatically iterate through a set of items, you can do:

try   {   //   ConfigNode N=Cs["Levels"];   foreach(ConfigNode C in N.Children)        {        Console.WriteLine("{0}",C.AsString());        }   }catch(...) // etc

Here's a recursive function that would list every item in a config file:

public void f(){    try        {        ConfigStream Cs=new ConfigStream("settings.cfg");        Output(Cs.Root);        }    catch(ConfigStreamException E)        {        // Error        }}pubic void Output(ConfigNode N){    foreach(ConfigNode C in N.Children)        {        Console.WriteLine("{0}={1}",C.Name,C.AsString());        Output(C);        }}

Much simpler that XML but easier to use and it was good fun writing it.

There are no comments to display.