Changing connectionStrings from the app.config physically in Runtime

Asked

Viewed 1,593 times

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 connectionString physically in Runtime?

4 answers

2

If you want to change the 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 in memory, this is the file app.config will not be changed.

  • I’ve done it, but as you said, it’s only changed in memory. I’d like to physically alter.

1

The way I physically change Connectionstring on 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();

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’s not just updating in memory, it’s playing to the file, needed a code to change only in memory, someone knows?

-2

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

In case you need the modifications in memory after physical change you will need to reload or set in memory at the same time that physically.

  • there is a way ready yes

  • Living and learning!!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.