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

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

问题描述

我想设置一个连接字符串编程,完全没有改变任何配置文件/注册表项。

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

我有这块code,但不幸的是它抛出一个异常,配置是只读的。

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);

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

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