//This post was substantially pirated from a 2006 post (author unknown). The key is to save, reload and refreshsection, as outlined in the last three lines of the code. If you miss any of these, you will not get the desired result. //1. Set a Reference to "System.Configuration.dll" in the project references. //2. Add the "using System.Configuration" class to the top of the code that calls the procedure below //3. Add a procedure, that assumes fully qualified "Connection String" named "MyAPP.Properties.Settings.MyConnection" where "MyAPP" is your executable and "MyConnection" is the name of the connection string in the application settings. //Change Your Connection String Dynamically (Before Making Any Data Calls) public static void ChangeConnectionString(string strConnectionNew) { //Instantiate A Configuration Object Configuration objConfiguration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); //Specify the full name of the connection string from the app.config file in the "name" attribute of the connection string objConfiguration.ConnectionStrings.ConnectionStrings["MyAPP.Properties.Settings.MyConnection"].ConnectionString = strConnectionNew; //Save the updated configuration file objConfiguration.Save(ConfigurationSaveMode.Modified); //Reload the saved settings Properties.Settings.Default.Reload(); //Force changes to take effect so that we can start using this new connection string immediately ConfigurationManager.RefreshSection(objConfiguration.ConnectionStrings.SectionInformation.Name); }
↧
HOWTO Dynamically Set Connection String
↧