Reputation: 52241
I try to change connection string, but it is only change in memory, but not in App.Config file, below is the code I am using
System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.ConnectionStrings.ConnectionStrings[1].ConnectionString = "metadata=res://*/TCSModel.csdl|res://*/TCSModel.ssdl|res://*/TCSModel.msl;provider=System.Data.SqlClient;provider connection string='Data Source=" + cmbServerName.Text + ";Initial Catalog=" + cmbDatabase.Text + ";User ID=" + txtUserName.Text.Trim() + ";Password=" + txtPassword.Password + ";Persist Security Info=True;MultipleActiveResultSets=True'";
config.ConnectionStrings.ConnectionStrings[1].Name = "TCSEntities";
config.ConnectionStrings.ConnectionStrings[1].ProviderName = "System.Data.EntityClient";
config.Save(ConfigurationSaveMode.Full, true);
ConfigurationManager.RefreshSection("connectionStrings");
What is missing or wrong in the above code?
Upvotes: 1
Views: 4877
Reputation: 54148
It would be helpful if you could post your app.config file. How many connection strings does it contain on input? This code changes or sets the second in the list.
Try this to see what happens - clear the list and just set a new one with a single entry:
config.ConnectionStrings.ConnectionStrings.Clear();
config.ConnectionStrings.ConnectionStrings[0].ConnectionString = "metadata=res://*/TCSModel.csdl|res://*/TCSModel.ssdl|res://*/TCSModel.msl;provider=System.Data.SqlClient;provider connection string='Data Source=" + cmbServerName.Text + ";Initial Catalog=" + cmbDatabase.Text + ";User ID=" + txtUserName.Text.Trim() + ";Password=" + txtPassword.Password + ";Persist Security Info=True;MultipleActiveResultSets=True'";
config.ConnectionStrings.ConnectionStrings[0].Name = "TCSEntities";
config.ConnectionStrings.ConnectionStrings[0].ProviderName = "System.Data.EntityClient";
You could also try using SaveAs
to ensure you know where the revised version gets output.
Upvotes: 0
Reputation: 172270
Are you running your application in Visual Studio? If that is the case, Visual Studio creates a temporary configuration file yourApp.vshost.exe.Config
in your bin
directory. This file is updated by your code. Of course, during the next start, it is recreated (again copied from app.config
in your source code directory), so it looks like the save didn't work.
So, this is a problem that won't occur "in production".
Upvotes: 3