Why my code doesn't work
app.config
<connectionStrings>
<add name="string.name"
connectionString=""
providerName="System.Data.SqlClient" />
</connectionStrings>
in c#
private void addnewstring()
{
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.AppSettings.Settings.Remove("string.name");
config.AppSettings.Settings.Add("string.name", "new connection string");
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("connectionStrings");
}
code in c# doesn't change connection string in app.config
You need to be modifying the ConnectionStrings - your code is just accessing the Settings. Try this :
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.ConnectionStrings.ConnectionStrings.Remove("string.name");
config.ConnectionStrings.ConnectionStrings.Add(new ConnectionStringSettings("string.name", "new connection string"));
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("connectionStrings");
Try this, shold be work
var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
var connectionStringsSection = (ConnectionStringsSection)config.GetSection("connectionStrings");
connectionStringsSection.ConnectionStrings["string.name"].ConnectionString = "new connection string";
config.Save();
ConfigurationManager.RefreshSection("connectionStrings");
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.