subs
subs

Reputation: 2249

Unable to read newly added connection string from app.config file

I am adding a connection string at runtime to my App.config file as shown below:

ConnectionStringSettings connSettings = new ConnectionStringSettings("dbConnectionString", "Data Source=DBSERVERNAME,1111;Initial Catalog=DBNAME;Integrated Security=false;User ID=USERID;Password=PASSWORD");
            var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            config.ConnectionStrings.ConnectionStrings.Add(connSettings);
            config.Save();

This code is correctly adding the connectionstring to the app.config file.

And then I am trying to create a SqlConnectionStringBuilder class like this :

SqlConnectionStringBuilder destinationConnection = new SqlConnectionStringBuilder(ConfigurationManager.ConnectionStrings["dbConnectionString"].ConnectionString);

I am getting a null reference exception. Why am I getting the null refernce exception? What am I missing here?

Upvotes: 3

Views: 440

Answers (1)

Christian.K
Christian.K

Reputation: 49300

The configuration classes cache the read file. You need to refresh the respective configuration section, before you get the new values in code.

ConfigurationManager.RefreshSection("connectionStrings");

UPDATE: are you actually doing both, updating the app.config and trying to access the connection string, from the same process (and AppDomain)? Because refreshing the configuration section should not be necessary if so. If you paste both your fragments in the Main method of a console application it will work as expected without the refreshing of the section.

Upvotes: 3

Related Questions