是否可以在运行时更改app.config中的ConnectionString值?根据MSDN文档,应该可以使用ConnectionString属性“获取或设置连接字符串”。
我的代码如下所示:
ConnectionStringSettings mainConnection = ConfigurationManager.ConnectionStrings["mainConnection"]; mainConnection.ConnectionString = "Data Source=SERVER;Initial Catalog=" + NewDatabaseName + ";Integrated Security=True";
我收到的错误是:“未处理的异常:System.Configuration.ConfigurationErrorsException:配置为只读。”
Configuration myConfiguration = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~"); myConfiguration.ConnectionStrings.ConnectionStrings("myDatabaseName").ConnectionString = txtConnectionString.Text; myConfiguration.AppSettings.Settings.Item("myKey").Value = txtmyKey.Text; myConfiguration.Save();
参考:http : //www.beansoftware.com/ASP.NET-Tutorials/Modify-Web.Config-Run- Time.aspx