Changing app.config connectionStrings physically in runtime

6

In my app.config I have the following lines of code:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <configSections>
    </configSections>
    <connectionStrings>
        <add name="ControleBD"
            connectionString="Data Source=SERVIDOR\SQLEXPRESS;Initial Catalog=Controle;User ID=Adminx;Password=123456"
            providerName="System.Data.SqlClient" />
    </connectionStrings>
</configuration>

How do I change the value of the connectionString physically in runtime?

    
asked by anonymous 22.07.2014 / 16:26

4 answers

2

If you want to change connection string during the runtime:

var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
var connectionString = (ConnectionStringsSection) config.GetSection("connectionStrings");
connectionString.ConnectionStrings["ControleBD"].ConnectionString = "Data Source=NewSource;Initial Catalog=NewCatalog;UID=NewUser;password=NewPassword";
config.Save();
ConfigurationManager.RefreshSection("connectionStrings");

Note that the code behind only changes the connection string into memory, ie the app.config file will not change.

    
22.07.2014 / 16:37
1

The way I physically change the ConnectionString in web.config is as follows:

Configuration webConfigApp = WebConfigurationManager.OpenWebConfiguration("~");
webConfigApp.ConnectionStrings.ConnectionStrings["ConnectionString"].ConnectionString = "Data Source=NewSource;Initial Catalog=NewCatalog;UID=NewUser;password=NewPassword";
webConfigApp.Save();
    
22.07.2014 / 19:19
0
var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
var connectionString = (ConnectionStringsSection) config.GetSection("connectionStrings");
connectionString.ConnectionStrings["ControleBD"].ConnectionString = "Data Source=NewSource;Initial Catalog=NewCatalog;UID=NewUser;password=NewPassword";
config.Save();
ConfigurationManager.RefreshSection("connectionStrings");

I used this code, but it is not only updating in memory, it is playing to the file, I needed a code to only change in memory, does anyone know?

    
29.05.2016 / 23:29
-2

You can change the file physically (XML), just change where you need it, there is no ready way for it.

If you need the changes in memory after a physical change, you will need to reload or remain in memory at the same time as physically.

    
22.07.2014 / 17:49