更新connectionString值无效

时间:2016-01-20 21:39:35

标签: c# runtime connection-string

我试图在运行时更新一些配置文件。正在更新一个文件,但未更改connectionString值。

这是我的代码

Configuration config = WebConfigurationManager.OpenWebConfiguration("/");
config.AppSettings.Settings["ServerDSN"].Value=newValue;
config.Save(ConfigurationSaveMode.Modified);
System.Data.EntityClient.EntityConnectionStringBuilder builder = null;

foreach (ConnectionStringSettings connString in ConfigurationManager.ConnectionStrings)
{
    if (connString.Name == "myConnectionString")
    {
        Configuration config2 = WebConfigurationManager.OpenWebConfiguration("/");
        //Configuration config2 = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
        builder = new EntityConnectionStringBuilder(connString.ToString());
        builder.ProviderConnectionString = string.Format(";database Name={0};host=localhost;", db);
        config2.Save(ConfigurationSaveMode.Modified, true);
        ConfigurationManager.RefreshSection("connectionStrings");
    }
}

感谢

1 个答案:

答案 0 :(得分:1)

尝试使用

Configuration config = WebConfigurationManager.OpenWebConfiguration("/");
config.AppSettings.Settings["ServerDSN"].Value=newValue;
config.ConnectionStrings.ConnectionStrings["myConnectionString"].ConnectionString = string.Format(";database Name={0};host=localhost;", db);
config.Save();