Click here to Skip to main content
15,903,362 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to change app config connection string, through a code

My SourceCode

C#
string connString = "";

connString = "Data Source=" + Convert.ToString(txtServer.EditValue) + ";" + 
             "Initial Catalog=" + Convert.ToString(txtDatabase.EditValue) + ";" +
             "User id=" + Convert.ToString(txtUserName.EditValue) + ";" +
             "Password=" + Convert.ToString(txtPassword.EditValue) + ";";

var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
ConnectionStringsSection connSection =    
    (ConnectionStringsSection)config.GetSection("connectionStrings");
connSection.ConnectionStrings["INATTSQLConnString"].ConnectionString = connString;
config.Save();
ConfigurationManager.RefreshSection("connectionStrings");


but when i saw in my app.config, this file isn't modified.

can somebody help me, please?

Thanks
Posted
Comments
Vi(ky 5-Jun-14 10:32am    
Once check YourAppName.vshost.exe.config in debug or release folder in bin directory of project.

1 solution

This has been tested to work. The only difference is that it omits the "GetSection".
Remember that if you are testing this in a debug session and you are using the vs host, this change will be applied to the appName.vshost.exe.Config file.
public static void ModifyConnectionString(string connectionString)
{
   Configuration config =             
      ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
   ConnectionStringSettingsCollection connectionStrings = 
      config.ConnectionStrings.ConnectionStrings;
   connectionStrings["INATTSQLConnString"].ConnectionString = connectionString;
   config.Save();

    ConfigurationManager.RefreshSection("connectionStrings");
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900