How to Modify app.config at Runtime

By FoxLearn 1/21/2025 7:43:22 AM   26
When trying to modify the app.config at runtime, it's essential to handle it correctly to avoid errors like:
  • System.Configuration.ConfigurationErrorsException: The configuration is read only.
  • The updated values aren't persisted upon reopening the program, the old values reappear.

In this article, we’ll explore how to update the app.config file correctly to prevent these issues. We will discuss three different scenarios: adding a new connection string, modifying an existing connection string, and updating an app setting value.

The app.config file is an XML-based configuration file used in .NET Framework applications. In newer versions of .NET (like .NET Core), the config file is named appsettings.json and is JSON-based.

Here is the example app.config we will use, focusing on the appSettings and connectionStrings sections:

<?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="test"/>
    </appSettings>
    <connectionStrings>
        <add name="test" connectionString="Data Source=.;Initial Catalog=test;Integrated Security=True"/>
    </connectionStrings>
</configuration>

When the application is running, app.config is renamed to ExecutableName.exe.config.

Inserting a New Connection String

To insert a new connection string into the connectionStrings section, use the following method:

/// <summary>
/// Saves a new connection string to the application's configuration file.
/// </summary>
/// <param name="name">The name of the connection string.</param>
/// <param name="connectionString">The connection string to be saved.</param>
private void SaveConnectionString(string name, string connectionString)
{
    // Create a new ConnectionStringSettings object using the provided name and connection string.
    var conStringSetting = new ConnectionStringSettings(name, connectionString);

    // Open the configuration file for the application.
    var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

    // Add the new connection string to the collection of connection strings in the configuration.
    config.ConnectionStrings.ConnectionStrings.Add(conStringSetting);

    // Save the changes made to the configuration file.
    config.Save(ConfigurationSaveMode.Modified);

    // Refresh the "connectionStrings" section to ensure the updated settings are applied immediately.
    ConfigurationManager.RefreshSection("connectionStrings");
}

Usage:

// Create a new SqlConnectionStringBuilder object to build the connection string
var sqlConBuilder = new SqlConnectionStringBuilder()
{
    // Set the database name (InitialCatalog) for the connection string
    InitialCatalog = "myDb",

    // Set the data source (server) for the connection string
    DataSource = ".",

    // Enable integrated security (Windows authentication) for the connection
    IntegratedSecurity = true
};

// Save the generated connection string with the name "mydb" using the SaveConnectionString method
SaveConnectionString("mydb", sqlConBuilder.ConnectionString);

This inserts a new connection string myDb into the ExecutableName.exe.config file, resulting in:

<connectionStrings>
    <add name="test" connectionString="Data Source=.;Initial Catalog=test;Integrated Security=True"/>
    <add name="mydb" connectionString="Data Source=.;Initial Catalog=myDb;Integrated Security=True"/>
</connectionStrings>

Modifying an Existing Connection String

To modify an existing connection string, use the following code:

/// <summary>
/// Modifies an existing connection string in the application's configuration file.
/// </summary>
/// <param name="name">The name of the connection string to modify.</param>
/// <param name="connectionString">The new connection string to set.</param>
private void ModifyConnectionString(string name, string connectionString)
{
    // Open the configuration file for the application.
    var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

    // Retrieve the "connectionStrings" section from the configuration file.
    var section = (ConnectionStringsSection)config.GetSection("connectionStrings");

    // Modify the connection string with the specified name by setting its value to the new connection string.
    section.ConnectionStrings[name].ConnectionString = connectionString;

    // Save the modified configuration file.
    config.Save(ConfigurationSaveMode.Modified);

    // Refresh the "connectionStrings" section to ensure the updated settings are applied immediately.
    ConfigurationManager.RefreshSection("connectionStrings");
}

Usage:

var sqlConBuilder = new SqlConnectionStringBuilder()
{
    InitialCatalog = "db",
    DataSource = "192.168.1.100",
    IntegratedSecurity = true
};

ModifyConnectionString("mydb", sqlConBuilder.ConnectionString);

This modifies the mydb connection string in the ExecutableName.exe.config file, updating it to:

<connectionStrings>
    <add name="test" connectionString="Data Source=.;Initial Catalog=test;Integrated Security=True"/>
    <add name="mydb" connectionString="Data Source=192.168.1.100;Initial Catalog=db;Integrated Security=True"/>
</connectionStrings>

Updating an appSettings Value

To modify a setting in the appSettings section, use the following code:

/// <summary>
/// Sets the default connection string name in the application's configuration file.
/// </summary>
/// <param name="connectionStringName">The name of the connection string to set as default.</param>
private void SetDefaultConnectionString(string connectionStringName)
{
    // Open the configuration file for the application.
    var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

    // Set the value of the "DefaultConnectionStringName" app setting to the provided connection string name.
    config.AppSettings.Settings["DefaultConnectionStringName"].Value = connectionStringName;

    // Save the modified configuration file.
    config.Save(ConfigurationSaveMode.Modified);

    // Refresh the "appSettings" section to ensure the updated setting is applied immediately.
    ConfigurationManager.RefreshSection("appSettings");
}

Usage:

SetDefaultConnectionString("mydb");

This modifies the DefaultConnectionStringName setting to mydb in the ExecutableName.exe.config file, resulting in:

<appSettings>
    <add key="DefaultConnectionStringName" value="mydb"/>
</appSettings>

If you attempt to update the app.config while the application is located in restricted directories (such as /Program Files/), you may encounter the following error:

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

To resolve this, either run the application with administrative privileges or modify the file's permissions to allow write access.