Had to do this exact thing. This is the code that worked for me:
var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
var connectionStringsSection = (ConnectionStringsSection)config.GetSection("connectionStrings");
connectionStringsSection.ConnectionStrings["Blah"].ConnectionString = "Data Source=blah;Initial Catalog=blah;UID=blah;password=blah";
config.Save();
ConfigurationManager.RefreshSection("connectionStrings");
IIRC, the ConfigurationManager.RefreshSection requires a string parameter specifying the name of the Section to refresh :
ConfigurationManager.RefreshSection("connectionStrings");
I think that the ASP.NET application should automatically reload when the ConnectionStrings element is modified and the configuration does not need to be manually reloaded.
//You can apply the logic in "Program.cs"
//Logic for getting new connection string
//****
//
MyDBName="mydb";
//
//****
//Assign new connection string to a variable
string newCnnStr = a="Data Source=.\SQLExpress;Initial Catalog=" + MyDBName + ";Persist Security Info=True;User ID=sa;Password=mypwd";
//And Finally replace the value of setting
Properties.Settings.Default["Nameof_ConnectionString_inSettingFile"] = newCnnStr;
//This method replaces the value at run time and also don't needs app.config for the same setting. It will have the va;ue till the application runs.
//It worked for me.
Yeah, when ASP.NET web.config gets updated, the whole application gets restarted which means the web.config gets reloaded.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With