3

I have been looking in the web.config at some legacy code, where under most of the group sections before each <add...> a <remove...> was added, for example:

<connectionStrings>
    <remove name="abcDb" />
    <add name="abcDb" connectionString="..." providerName="System.Data.SqlClient" />

</connectionStrings>

If the section was added in the machine config file for some bizarre reason, is it not enough to just add the same section again and this gets overwritten?

Unless I'm missing a trick, why would we <remove> and then <add> and not just <add>

r.net
  • 601
  • 7
  • 16

2 Answers2

3

If you <add ... an element that has already been added in a higher level configuration file, it's not allowed (unless the value exactly matches).

When you attempt to access your connection string (or otherwise cause that configuration section to be loaded), you'll get an error:

The entry 'LocalSqlServer' has already been added.

Line 12:   </appSettings>
Line 13:  <connectionStrings>
Line 14:      <add name="LocalSqlServer" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|fruitbat.mdf;User Instance=true" providerName="System.Data.SqlClient"/>
Line 15:  </connectionStrings>
Line 16:   <system.web>

So that's why you should <remove ... (or, my preference, a plain <clear/>) before adding your own values that may have been configured elsewhere.


(Here, I added a LocalSqlServer connection string to my web.config, despite the fact that such a connection is already configured in the machine.config by default in later frameworks)

Damien_The_Unbeliever
  • 234,701
  • 27
  • 340
  • 448
1

you mostly use remove tag while deploying to multiple environments. Check this site which helps you to transform your web.config.

https://webconfigtransformationtester.apphb.com/

Basically it removes the the key "abcDb" and re-adds the same key with a different value based the environment you are trying to deploy.

IamChandu
  • 355
  • 6
  • 18
  • Is it not enough just to add ? – r.net Sep 11 '18 at 09:31
  • Add same key and value works with no issues. If you need to change the value of connection string in Prod through CI-CD process this is one of the ways to achieve it. – IamChandu Sep 11 '18 at 09:36
  • for production through CI-CD etc, we would normally use "web.release.config" etc, I still see no reason why we need to "remove" before "add"-ing. Thanks for your answer though. – r.net Sep 11 '18 at 10:07