How to modify app.config at runtime

When you try to modify the app.config at runtime, if you don’t do it right, you’ll run into a few problems:

  • You’ll get the following exception:

System.Configuration.ConfigurationErrorsException: The configuration is read only.

  • The updated value isn’t persisted. When you re-open your program, the value you changed is still the old value.

This article will show you how to update the app.config the right way to avoid these problems.

Example app – insert a new connection string

Imagine you have a program that connects to a database. The users want a way to specify the database connection without having to manually modify the app.config.

So you’ve built them the following form:

Windows Form allowing you to enter and save the connection string in the app.config

This form inserts the specified connection string into the connectionString section, and then updates the setting called DefaultConnectionStringName in the appSettings section.

The app.config file looks like this:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
    </startup>
  <appSettings>
    <add key="DefaultConnectionStringName" value="TestSQL"/>
  </appSettings>
    <connectionStrings>
        <add name="TestSQL" connectionString="Data Source=QAServer;Initial Catalog=BirdsDB;Integrated Security=True"/>
    </connectionStrings>
</configuration>

Code

Updating the connectionStrings section

private void SaveConnectionString(string name, string connectionString)
{
	var conStringSetting = new ConnectionStringSettings(name, connectionString);

	var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
	config.ConnectionStrings.ConnectionStrings.Add(conStringSetting);
	config.Save(ConfigurationSaveMode.Modified);

	ConfigurationManager.RefreshSection("connectionStrings");

}

Updating the appSettings section

private void SetDefaultConnectionString(string connectionStringName)
{
	var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
	config.AppSettings.Settings["DefaultConnectionStringName"].Value = connectionStringName;
	config.Save(ConfigurationSaveMode.Modified);

	ConfigurationManager.RefreshSection("appSettings");
}

Warning: Watch out for access errors

If you try to update the app.config at runtime while running the exe from /Program Files/ you’ll run into the following error:

System.Configuration.ConfigurationErrorsException: An error occurred loading a configuration file: Access to the path is denied.

You can run your app as admin or put proper permissions to overcome this problem.

Leave a Comment