你可以在运行时更改ConnectionString的配置价值

你可以在运行时更改ConnectionString的配置价值

本文介绍了你可以在运行时更改ConnectionString的配置价值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能改变一个的app.config在运行时连接字符串值?据the MSDN文档应该尽可能ConnectionString属性获取或设置连接字符串。

我的code是这样的:

  ConnectionStringSettings mainConnection = ConfigurationManager.ConnectionStrings [mainConnection];
mainConnection.ConnectionString =数据源=服务器;初始目录=+ NewDatabaseName +;集成安全性=真;
 

这是我收到的错误是这样的:未处理的异常:System.Configuration.ConfigurationErrorsException:该配置是只读的。

解决方案

 配置myConfiguration = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(〜);
    myConfiguration.ConnectionStrings.ConnectionStrings(myDatabaseName)的ConnectionString = txtConnectionString.Text。
    myConfiguration.AppSettings.Settings.Item(的myKey)值= txtmyKey.Text。
    myConfiguration.Save();
 

编号:http://www.beansoftware.com/ASP.NET-Tutorials/Modify-Web.Config-Run-Time.aspx

Is it possible to change the ConnectionString value in a app.config at runtime? According to the MSDN documentation it should be possible as the ConnectionString property "Gets or sets the connection string."

My code looks like this:

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

The error that I receive is this: "Unhandled Exception: System.Configuration.ConfigurationErrorsException: The configuration is read only."

解决方案
Configuration myConfiguration = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
    myConfiguration.ConnectionStrings.ConnectionStrings("myDatabaseName").ConnectionString = txtConnectionString.Text;
    myConfiguration.AppSettings.Settings.Item("myKey").Value = txtmyKey.Text;
    myConfiguration.Save();

Ref: http://www.beansoftware.com/ASP.NET-Tutorials/Modify-Web.Config-Run-Time.aspx

这篇关于你可以在运行时更改ConnectionString的配置价值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-06 01:59