如何在.net中编程设置连接字符串配置? [英] How do I set a connection string config programatically in .net?

查看:134
本文介绍了如何在.net中编程设置连接字符串配置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想以编程方式设置连接字符串,绝对不会更改任何配置文件/注册表项。

I'd like to set a connection string programmatically, with absolutely no change to any config files / registry keys.

我有这段代码,但不幸的是它会抛出配置是只读的异常。

I have this piece of code, but unfortunately it throws an exception with "the configuration is read only".

ConfigurationManager.ConnectionStrings.Clear();
string connectionString = "Server=myserver;Port=8080;Database=my_db;...";
ConnectionStringSettings connectionStringSettings = 
  new ConnectionStringSettings("MyConnectionStringKey", connectionString);
ConfigurationManager.ConnectionStrings.Add(connectionStringSettings);

编辑:
问题是,从配置读取连接字符串。所以设置配置字符串手动,或通过资源,似乎不是有效的选项。我真正需要的是一种以编程方式修改配置的方法。

The problem is that I have existing code that reads the connection string from the configuration. So setting the config string manually, or through a resource, don't seem like valid options. What I really need is a way to modify the configuration programmatically.

推荐答案

http://davidgardiner.blogspot.com/2008/09/programmatically-setting.html =nofollow noreferrer>在我的博客上发布信息。诀窍是使用反射来打开值,以获取对非公共字段(和方法)的访问。

I've written about this in a post on my blog. The trick is to use reflection to poke values in as a way to get access to the non-public fields (and methods).

例如。

var settings = ConfigurationManager.ConnectionStrings[ 0 ];

var fi = typeof( ConfigurationElement ).GetField( "_bReadOnly", BindingFlags.Instance | BindingFlags.NonPublic );

fi.SetValue(settings, false);

settings.ConnectionString = "Data Source=Something";

这篇关于如何在.net中编程设置连接字符串配置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆