Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I Add ConnectionStrings to the ConnectionStringCollection at Runtime?

Tags:

Is there a way where I can add a connection string to the ConnectionStringCollection returned by the ConfigurationManager at runtime in an Asp.Net application?

I have tried the following but am told that the configuration file is readonly.

ConfigurationManager.ConnectionStrings.Add(new ConnectionStringSettings(params));

Is there another way to do this at runtime? I know at design time I can add a connection string to the web.config; however, I'm looking to add something to that collection at run time.

Thanks

EDIT: One of the reasons why I'm attempting to do this is due to a security requirement that prevents me from placing ConnectionStrings in the web.config (even encrypted). I would like to use elements like Membership and Profiles on my project; however, I am looking into an alternative to doing such w/o writing a custom provider. Custom Provider's aren't all that bad, but if I can find an easier solution, I'm all for it.

like image 921
JamesEggers Avatar asked Dec 10 '08 20:12

JamesEggers


People also ask

How do I configure ConfigurationManager connectionStrings?

To read the connection string into your code, use the ConfigurationManager class. string connStr = ConfigurationManager. ConnectionStrings["myConnectionString"].

Where are connectionStrings stored?

Connection strings can be stored as key/value pairs in the connectionStrings section of the configuration element of an application configuration file. Child elements include add, clear, and remove. The following configuration file fragment demonstrates the schema and syntax for storing a connection string.


2 Answers

You can use reflection to disable the private bReadOnly field (bad idea, etc.):

typeof(ConfigurationElementCollection)
    .GetField("bReadOnly", BindingFlags.Instance | BindingFlags.NonPublic)
    .SetValue(ConfigurationManager.ConnectionStrings, false);
ConfigurationManager.ConnectionStrings.Add(new ConnectionStringSettings());

This is similar to the technique required to modify an existing connection string, and added as a comment there by Brian Rodgers.

like image 169
user423430 Avatar answered Sep 24 '22 06:09

user423430


var cfg = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(@"/");
cfg.ConnectionStrings.ConnectionStrings.Add(new ConnectionStringSettings(params));

cfg.Save();

Be Advised this will cause your website to recycle since it modifies the config file. Check out http://msdn.microsoft.com/en-us/library/4c2kcht0(VS.80).aspx

like image 38
JoshBerke Avatar answered Sep 24 '22 06:09

JoshBerke