小编典典

您可以在运行时更改ConnectionString配置值吗?

sql

是否可以在运行时更改app.config中的ConnectionString值?根据MSDN文档,应该可以使用ConnectionString属性“获取或设置连接字符串”。

我的代码如下所示:

ConnectionStringSettings mainConnection = ConfigurationManager.ConnectionStrings["mainConnection"];
mainConnection.ConnectionString = "Data Source=SERVER;Initial Catalog=" + NewDatabaseName + ";Integrated Security=True";

我收到的错误是:“未处理的异常:System.Configuration.ConfigurationErrorsException:配置为只读。”


阅读 152

收藏
2021-05-16

共1个答案

小编典典

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

2021-05-16