Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I set a connection string config programmatically in .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); 

Edit: 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.

like image 225
ripper234 Avatar asked Dec 11 '08 16:12

ripper234


People also ask

How do I reference a connection string in web config?

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

How do I configure ConfigurationManager ConnectionStrings?

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

How do I create a connection string in Web API?

Add a connection string property to the appSettings. json file and refer to your DbContext class inside Startup. cs file along with connection string. You will be all set to call your API to connect to a single SQL database for now.


1 Answers

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

eg.

var settings = ConfigurationManager.ConnectionStrings[ 0 ];  var fi = typeof( ConfigurationElement ).GetField( "_bReadOnly", BindingFlags.Instance | BindingFlags.NonPublic );  fi.SetValue(settings, false);  settings.ConnectionString = "Data Source=Something"; 
like image 186
David Gardiner Avatar answered Oct 17 '22 01:10

David Gardiner