tags:

views:

401

answers:

5

I've got a strange thing happening with my app.config file. My ConnectionStrings section contains this:

<connectionStrings>
  <add name="Connection" connectionString="Data Source=TheServer;
   Initial Catalog=TheDatabase;IntegratedSecurity=SSPI" 
   providerName="System.Data.SqlClient"/>
</connectionStrings>

However, when I query the section via ConfigurationManager.ConnectionStrings[0], I get back this connection string:

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

Where is it getting this value from?

+1  A: 

It comes from machine.config. .NET Automatically merges the connection string sections (and some others I believe) of your application config (or web config) and your machine.config.

You can read about how it works in ASP.NET here.

Jason Punyon
I see. Thank you. Why isn't it referencing the app.config file then? I haven't had this happen before.
woodstock
@woodstock: it is, but you are calling it by the index, and 0 happens to be the first one defined up in the hierarchy
Pawel Krakowiak
+1  A: 

It's coming from another config, either a higher up app.config in the tree or the machine config. To ignore anything else use <clear /> to get rid of anything not in the current config.

<connectionStrings>
   <clear />
   <add name="Connection" connectionString="Data Source=TheServer;
     Initial Catalog=TheDatabase;IntegratedSecurity=SSPI" 
     providerName="System.Data.SqlClient"/>
</connectionStrings>
DeletedAccount
+4  A: 

It is read from machine.config, you can either make sure to clear all connection strings before adding your own:

<connectionStrings>
  <clear/>
  <add name="Connection" connectionString="Data Source=TheServer;
   Initial Catalog=TheDatabase;IntegratedSecurity=SSPI" 
   providerName="System.Data.SqlClient"/>
</connectionStrings>

Or just never reference your connection strings by indexes, use names you give them:

ConfigurationManager.ConnectionStrings["Connection"]
Pawel Krakowiak
I believe this is the correct answer, beat me to it.
Chris Needham
A: 

Addition to Nath's answer, this is better :

ConfigurationManager.ConnectionStrings["Connection"]
Canavar
A: 

Although the question's been answered by Jason Punyon, I'd strongly recommend accessing your connection strings via their name rather than their index. e.g.

ConfigurationManager.ConnectionStrings["Connection"]
mdresser
Oops, a bit late there...
mdresser