Showing posts with label Configuration. Show all posts
Showing posts with label Configuration. Show all posts

Thursday, August 27, 2009

Reading Data from the Configuration (*.config) File

In the previous post I saved data to the config file. Here is an example of how you would read data from the config file:
if (ConfigurationManager.AppSettings["Width"] != null)
{
    this.Width = Convert.ToDouble(ConfigurationManager.AppSettings["Width"]);
}

if (ConfigurationManager.AppSettings["Height"] != null)
{
    this.Height = Convert.ToDouble(ConfigurationManager.AppSettings["Height"]);
}


More Info: MSDN: ConfigurationManager.AppSettings

Saving Data to the Configuration (*.config) File

Sometimes you want to save data to the configuration file so it's available the next time the application runs. An example of this is saving a window's last height and width upon closing. Here's how you do it:
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

config.AppSettings.Settings.Remove("Width");
config.AppSettings.Settings.Add("Width", this.Width.ToString());
config.AppSettings.Settings.Remove("Height");
config.AppSettings.Settings.Add("Height", this.Height.ToString());

config.Save(ConfigurationSaveMode.Modified);

Mark, why do I have to call the Remove method before adding?

Every time you call the Add method it appends data instead of overwriting it. Without calling the Remove method your configuration file will go from this:
<configuration>
    <appSettings>
        <add key="Width" value="402" />
        <add key="Height" value="177" />
    </appSettings>
</configuration>
to this on the next save:
<configuration>
    <appSettings>
        <add key="Width" value="402,300" />
        <add key="Height" value="177,154" />
    </appSettings>
</configuration>
More Info: MSDN: Configuration Class