如何动态更改为web.config中的连接字符串 [英] how to change to connection string in web.config dynamically
问题描述
我在web.config中找到了连接字符串
< ConnectionStrings><添加name ="student" connectionString ="Server = student;最大池大小= 300;初始目录= studentDB;用户ID = student;密码= st123dent;"providerName ="System.Data.SqlClient"/></连接字符串>
如何在C#中动态更改连接字符串
配置是只读的,因此您不能像
这样的明显方式进行配置 ConfigurationManager.ConnectionStrings ["student"].ConnectionString =新值";
这会引发 System.Configuration.ConfigurationErrorsException 异常上面写着配置是只读的".
这是一个使用反射来重置配置元素的readOnly属性的技巧.有关详细信息,请参见本文以编程方式设置connectionString属性 >
代码段:
var设置= ConfigurationManager.ConnectionStrings [0];var fi = typeof(ConfigurationElement).GetField("_bReadOnly",BindingFlags.Instance |BindingFlags.NonPublic);fi.SetValue(settings,false);settings.ConnectionString =数据源=某事";
顺便说一句,为什么您需要更改其配置?我感觉到您正在尝试以错误的方式解决某些问题.
I defind the connection string in web.config
<ConnectionStrings>
<add name="student" connectionString="Server=student;Max Pool Size=300;Initial Catalog=studentDB;User ID=student;Password=st123dent;" providerName="System.Data.SqlClient"/>
</Connectionstrings>
how can i change the connection string dynamically in c#
Configuration is read only so you can not do it in obvious way like
ConfigurationManager.ConnectionStrings["student"].ConnectionString = "new value";
This raises System.Configuration.ConfigurationErrorsException exception which saying that "Configuration is read only".
Here is a trick using reflection to reset readOnly attribute of configuration element. See this article for full details Programmatically setting a connectionString property
Code snippet:
var settings = ConfigurationManager.ConnectionStrings[ 0 ];
var fi = typeof(ConfigurationElement).GetField(
"_bReadOnly",
BindingFlags.Instance | BindingFlags.NonPublic);
fi.SetValue(settings, false);
settings.ConnectionString = "Data Source=Something";
BTW, why you need change it the configuration? I'm feeling that you'are trying to solve some problem in wrong way.
这篇关于如何动态更改为web.config中的连接字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!