How to dynamically change connection string in web.config

Most of people wonder how they can dynamically change the contents of web.config file. To simplify things I have created couple of functions through which you can change the contents of web.config file. Here is the code to change the contents of web.config file:-

/// <summary>

/// Updates the setting.

/// </summary>

/// <param name="key">The key.</param>

/// <param name="value">The value.</param>

public void UpdateSetting(string key, string value)

{

    Configuration config = WebConfigurationManager.OpenWebConfiguration("~");

    if (config.AppSettings.Settings[key] == null)

    {

        config.AppSettings.Settings.Add(key, value);

    }

    else

    {

        config.AppSettings.Settings[key].Value = value;

    }

    config.Save();

    ConfigurationManager.RefreshSection("appSettings");

}

 

/// <summary>

/// Updates the connection string.

/// </summary>

/// <param name="key">The key.</param>

/// <param name="value">The value.</param>

public void UpdateConnectionString(string key, string value)

{

    Configuration config = WebConfigurationManager.OpenWebConfiguration("~");

    if (config.ConnectionStrings.ConnectionStrings[key] == null)

    {

        config.ConnectionStrings.ConnectionStrings.Add(new ConnectionStringSettings(key, value));

    }

    else

    {

        config.ConnectionStrings.ConnectionStrings[key].ConnectionString = value;

    }

    config.Save();

    ConfigurationManager.RefreshSection("connectionStrings");

}


You can update the contents of web.cofig file by simply calling above functions like this:-

protected void Page_Load(object sender, EventArgs e)

{

    UpdateSetting("test", "123");

    UpdateConnectionString("testcon", "12345");

}