Matt
Matt

Reputation: 4117

C# Configuration Manager . ConnectionStrings

I have a console app containing an application configuration file containing one connection string as shown below:

<configuration>
  <connectionStrings>
    <add name="Target" 
      connectionString="server=MYSERVER; Database=MYDB; Integrated Security=SSPI;" />
  </connectionStrings>
</configuration>

When I pass this to my Connection using:

ConfigurationManager.ConnectionStrings[1].ToString()

I have two values in there, hence using the second in the collection, my question is where is this second coming from?

I have checked the \Bin version and original and its not mine! Its obviously a system generated one but I have not seen this before? Can anyone enlighten me?

The mystery connection string is:

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

This isn't a problem as such I would just like to know why this is occuring? Thanks in advance!

For future reference to those who may or may not stumble on this, after discovering the machine.config, it's become apparent it is bad practice to refer to a config by its index as each stack will potentially be different, which is why "Keys" are used.

In this instance my code would be:

ConfigurationManager.ConnectionStrings["Target"].ToString()

Cheers all!

Upvotes: 19

Views: 37519

Answers (4)

Ahmed Mahmoud Hamed
Ahmed Mahmoud Hamed

Reputation: 1

The Index first Element in the Connection Strings tag is stored By default And it's represents the > MemberShip database Connection String.

Cause of the Consideration for CLR is to be used during your application , So that the CLR On your behalf attaches it By default .

Like what is the CLR Doing with Default Constructor in the Class Creation without Constructor.

Upvotes: 0

Ryan Rinaldi
Ryan Rinaldi

Reputation: 4239

Check your machine.config. If you only want your entry, you can add a <clear /> element to the <connectionStrings> element like so ...

<connectionStrings>
  <clear />
  <add name="Target" 
       connectionString=
             "server=MYSERVER; Database=MYDB; Integrated Security=SSPI;" />
</connectionStrings>

Upvotes: 26

Toby
Toby

Reputation: 7544

It's defined in the machine.config file, and it's global to all .Net applications on the machine.

Connection strings "stack" through the configuration hierarchy, which is why the element name for your own connection string is tagged "add". You're adding your own connection string to the list of machine-level connection strings.

It might be preferable to use:

ConfigurationManager.ConnectionStrings["Target"].ConnectionString

to ensure you get your own connection string, even if the machine.config is modified.

Upvotes: 3

Adam V
Adam V

Reputation: 6356

Check your machine.config (under WindowsDir\Framework). I just checked mine and I have the same thing.

Upvotes: 3

Related Questions