I usually work with web pages but the other day I worked with a simple application to get some data from a file using the ODBC driver, but this desktop application must have some settings that I need to configure, here is where app.config file have their special moment.
Work with the app.config is like the web.config file talking about web projects, so its easy and very helpful to create a program with settings.
We need to add an app.config file to our project, just click in the Project, Add, New Item and select Application Configuration File.
Open the file and it will be like this (without the key setting, that is my default setting I added to the file) :
<?xml version="1.0" encoding="utf-8" ?> <configuration> <appSettings> <add key="setting" value="HelloWorld!"/> </appSettings> </configuration>
Then in code, we need the assembly we need to manage the configuration file:
Actually is very easy, to read a configuration just do this:
// Read values from configuration string setting = ConfigurationManager.AppSettings["setting"]; Console.WriteLine(setting);
To write a new value, remove an old one or modify an existent one, just do this:
// Write values from configuration // Modify Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); config.AppSettings.Settings["setting"].Value = "Hello_World!"; config.Save(ConfigurationSaveMode.Full); // Add config.AppSettings.Settings.Add("modifDate", DateTime.Now.ToLongTimeString() + " "); config.AppSettings.Settings.Add("modifDate2", DateTime.Now.ToLongTimeString() + " "); config.Save(ConfigurationSaveMode.Full); // Remove config.AppSettings.Settings.Remove("modifDate2"); config.Save(ConfigurationSaveMode.Full);
Ok now you can create settings for your application,