Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read connectionStrings element of your app.config

I am trying to read the connection strings from my app.config but it only shows me one connection string and that too isn't in my app.config.

Here's my code:

System.Diagnostics.Debugger.Break();

Configuration config = 
ConfigurationManager.OpenExeConfiguration(
                    AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);

foreach (var connectionString in config.ConnectionStrings.ConnectionStrings)
    System.Diagnostics.Debug.Print(connectionString.ToString());

And it prints out this:

data source=.\SQLEXPRESS;Integrated Security=SSPI;
   AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true

When I am expecting it to print out a custom connectionString to one of my databases that I have specified in the app.config file.

Update

Thank you all for spending time on my problem and trying to help out. Although all of you are right in that I could simply use ConfigurationManager.ConnectionStrings or access any other subsection this way, I believe when I do that, the configuration is read-only. I cannot make any changes to it, such as add a new connection string or remove an existing one. And I need to do that. Please let me know if there's a way to modify the config file at run-time.

like image 345
Water Cooler v2 Avatar asked Nov 24 '10 20:11

Water Cooler v2


1 Answers

It reads from your machine.config. After <connectionStrings> in app.config insert a <clear/>.

like image 108
Elena Avatar answered Nov 03 '22 07:11

Elena