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.
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>
/// Initializes a new instance of the <see cref="WindowSize"/> class.
public WindowSize() : base("WindowSize")
/// Gets or sets the section.
/// <value>The section.</value>
public override Size Value
Size size = new Size();
size.Width = GetInteger("Width", 640);
size.Height = GetInteger("Height", 480);
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();
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