Configuration in Windows .Net applications is not that easy as one would expect.
Of course, you have
Java example:
Properties propList = new Properties();
propList.load(new FileInputStream("PropertyTest.properties"));
propList.list(System.out);
propList.store(new FileOutputStream("PropertyTest.properties"), "Stored by this
program");
So, I wrote my own Configuration class for .Net, which allows a user to load and save properties to a file. It is very simple. It uses SoapFormatter to serialize Hashtable in a file.
Using it is very strait forward:
Configuration config = new Configuration();
// you can also pass a filename here (by default, it uses
// config.xml in the application directory Console.WriteLine(config.Get("Key"));
config.Put("key2", 25);
config.Save(); // Save is also called automagically
I might add events for when the configuration changes in the future, but for now, that is enough, I guess.
Source code + compiled binary is in the zip.
For example, I use this class in FileDownloader. In the constructor of the form, I try to load the values from the file. This of course fails on the first attempt and that is why I use createConfig method, plus I use Get method with default parameters as well. On form.Closing event, I save user supplied data so when the user starts the app next time, the values he/she last filled in are there.
public Form1()
{
config = new Configuration.Configuration(System.Environment.GetFolderPath(System.Environment.SpecialFolder.ApplicationData) + "\\FileDownloaderConfig.xml", false);
try
{
config.Load();
}
catch (System.IO.FileNotFoundException)
{
textBox1.Text += "[INFO] Configuration file not found!\r\n";
textBox1.Text += "[INFO] Creating new config...\r\n";
config.CreateConfig();
}
txtSource.Text = (string) config.Get("sourceDir", "");
txtDestination.Text = (string) config.Get("destinationDir", "");
txtPattern.Text = (string) config.Get("pattern", "yyyy_MM_dd");
}
private void Form1_Closed(object sender, System.EventArgs e)
{
if(config != null)
{
config.Put("sourceDir", txtSource.Text);
config.Put("destinationDir", txtDestination.Text);
config.Put("pattern", txtPattern.Text);
config.Save();
}
}
Of course, you can store other objects in there as well (for example, ArrayList).