Tutorial :app.config weirdness



Question:

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?


Solution:1

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"]  


Solution:2

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>  


Solution:3

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.


Solution:4

Addition to Nath's answer, this is better :

ConfigurationManager.ConnectionStrings["Connection"]  


Solution:5

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"]  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »