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:
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");
}
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");
}
then
protected void Page_Load(object sender, EventArgs e)
{
UpdateSetting("test", "123");
UpdateConnectionString("testcon", "12345");
}
http://zeeshanumardotnet.blogspot.in/2011/12/how-to-dynamically-change-connection.html[
^]
[
^]