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

查看:70
本文介绍了如何在.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.

推荐答案

我已经在在我的博客上发布。诀窍是使用反射来戳值,以获取对非公共字段(和方法)的访问权限。

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天全站免登陆