Change connection string & reload app.config at run time

When I change the connection string using this code, it does not reload app.config at runtime. I expected it to reload similarly to how we reload app.config.

config.ConnectionStrings.ConnectionStrings["JVVNL_NEW.Properties.Settings.JVVNL_NEWConnectionString1"].ConnectionString = ConString;
config.ConnectionStrings.ConnectionStrings["CMS_NEW.Properties.Settings.JVVNL_NEWConnectionString1"].ConnectionString = ConString;
config.Save(ConfigurationSaveMode.Modified,true);
ConfigurationManager.RefreshSection(config.ConnectionStrings.SectionInformation.SectionName);

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.