Dynamically change connectionString in web.config

I have the following in my web.config

<connectionStrings> <add name="ActiveDirectoryConnection" connectionString="LDAP://ActiveDirectoryDomain1.com" providerName="System.Web.Security.ActiveDirectoryMembershipProvider"/> </connectionStrings> 

I need to add a dropdown to my login page, which allows the user to change the connectionString to another line, for example. "LDAP: //ActiveDirectoryDomain2.com"

In C # code, how to change the value of connectionString?


Additional Information:

The problem I ran into is that there are 4 more other web.config parameters that are called a single String connection. For instance:

 <activeDirectorySecurityContextSettings connectionStringName="ActiveDirectoryConnection" defaultADUserName="ReportUser" defaultADPassword="password"/> 

Thanks!

+3
c # connection-string
source share
4 answers

If the user can change the value of the parameter, then the web.config file is the wrong place to store the settings.

Instead, you should check the User Area value in the settings file.

MSDN - Using Settings in C #

Using these settings, changing the value at run time is very simple:

 Properties.Settings.Default.LdapConnectionString = "New Connection String"; Properties.Settings.Default.Save(); 
+7
source share
  • It’s a good idea to modify the * .config file inside the program.
  • It is a bad idea for a web page to modify any file in the root folder of your site.
  • It’s a bad idea to have a permission set that allows a web page to modify files in the root folder of your site.

Basically, you need to forget about web.config and structure your code to use a connection string that exists only in memory.

+3
source share
 var settings = ConfigurationManager.ConnectionStrings[ 0 ]; var fi = typeof( ConfigurationElement ).GetField( "_bReadOnly", BindingFlags.Instance | BindingFlags.NonPublic ); fi.SetValue(settings, false); settings.ConnectionString = "Data Source=Something"; 
+2
source share

Even if it is a bad idea to modify the web.config inside the application, you can try the following:

 System.Configuration.ConfigurationManager.AppSettings.Set("keyToBeReplaced", "newKeyValue"); 
0
source share

All Articles