Because of the high resonance about the article “How to access INI Files in C# .NET” I want to introduce a blog entry on how to store configuration data into INI Files.
If you think about my last article, I told that it is very simple to access the INI File. But one question still stays up to date. How do I access the INI Files in a smart way?
Therefore I want to show you my best practices to access the INI File using the new template mechanism of .NET 2.0.
Let us define a structure or a class as an image of our section within the INI File. In my example this maybe the size of the window or it’s location.
[WindowSize]
Width=379
Height=290
[WindowLocation]
Left=131
Top=92
In order to this I developed a class template to map the values directly to the INI File. Look at this smart class that accesses the window size of the INI File above.
public class WindowSize : IniFileConfiguration<Size>
{
/// <summary>
/// Initializes a new instance of the <see cref="WindowSize"/> class.
/// </summary>
public WindowSize() : base("WindowSize")
{
}
/// <summary>
/// Gets or sets the section.
/// </summary>
/// <value>The section.</value>
public override Size Value
{
get
{
Size size = new Size();
size.Width = GetInteger("Width", 640);
size.Height = GetInteger("Height", 480);
return size;
}
set
{
SetInteger("Width", value.Width);
SetInteger("Height", value.Height);
}
}
}
The template structure has been set to Size and the constructor sets the section name that will be accessed. If you look at the example application you can use this simple code snipped to store the window position and it’s size.
public partial class Form1 : Form
{
private WindowSize windowSize = new WindowSize();
private WindowLocation windowLocation = new WindowLocation();
public Form1()
{
InitializeComponent();
}
private void OnLoad(object sender, EventArgs e)
{
Size = windowSize.Value;
Location = windowLocation.Value;
}
private void OnClose(object sender, FormClosedEventArgs e)
{
windowSize.Value = Size;
windowLocation.Value = Location;
}
}
That’s quite handy, isn’t it?
You can download the example application of this blog entry using the following link:
Best practice of storing configuration in INI Files with C# .NET
Wish you a merry christmas
Cheers
Gerhard