Dynamically change connectionString in web.config

前端 未结 4 1263
無奈伤痛
無奈伤痛 2020-12-19 22:11

I have the following in my web.config


   

        
相关标签:
4条回答
  • 2020-12-19 22:20

    Even if it's a bad idea to modify the web.config file from inside an app, you can try this:

    System.Configuration.ConfigurationManager.AppSettings.Set("keyToBeReplaced", "newKeyValue");
    
    0 讨论(0)
  • 2020-12-19 22:24
    • It's a bad idea to modify a *.config file from inside the program.
    • It's a bad idea for a webpage to modify any file in the root folder of your website.
    • It's a bad idea to have permission set allowing a web page the modification of files in the root folder of your website.

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

    0 讨论(0)
  • 2020-12-19 22:25

    If a user is able to change the value of the Setting, then the web.config file is the wrong place to store the setting.

    You should check out a User Scoped value in a Settings file instead.

    MSDN - Using Settings in C#

    When using settings like this, changing the value at runtime is easy:

    Properties.Settings.Default.LdapConnectionString = "New Connection String";
    Properties.Settings.Default.Save();
    
    0 讨论(0)
  • 2020-12-19 22:27
    var settings = ConfigurationManager.ConnectionStrings[ 0 ];
    
    var fi = typeof( ConfigurationElement ).GetField( "_bReadOnly", BindingFlags.Instance | BindingFlags.NonPublic );
    
    fi.SetValue(settings, false);
    
    settings.ConnectionString = "Data Source=Something";
    
    0 讨论(0)
提交回复
热议问题