How to remove a ConnectionString using Config Transformations

C#.NetVisual StudioWeb ConfigWeb Config-Transform

C# Problem Overview


I have a Web.config with several ConnectionStrings

<connectionStrings>
    <add name="connStr1" connectionString="...
    <add name="ConnStr2" connectionString="...
    <add name="connStr3" connectionString="...

Is there a way using config transformations to remove a specific connectionstring? Something Like:

<connectionStrings>
    <xdt:Remove connStr2?

Obviously no where near the correct syntax, but you get my drift...

C# Solutions


Solution 1 - C#

This will remove a specific connection string based on its name.

<configuration>
  <connectionStrings> 
    <add name="ConnStr2" xdt:Transform="Remove" xdt:Locator="Match(name)" connectionString=" " /> 
  </connectionStrings> 
</configuration>

Note that the connectionString value is not empty string, but is instead a space. Any non-empty value would do.

Solution 2 - C#

From the MSDN documentation on the subject:

<configuration xmlns:xdt="...">
  <connectionStrings>
    <add xdt:Transform="Remove" />
  </connectionStrings>
</configuration>

The Transform="Remove" is the magic you're looking for. There is also a Transform="RemoveAll" which you might be able to use in conjunction with a specific add(s).

EDIT

On second thought you may also be able to combine the Locator attribute with the Remove defined above to limit which elements you actually want to delete.

More definitively:

<configuration xmlns:xdt="...">
  <connectionStrings>
    <add xdt:Transform="Remove" xdt:Locator="XPath(configuration/connectionStrings[@name='ConnStr2'])" />
  </connectionStrings>
</configuration>

Or similar should work.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDidaxisView Question on Stackoverflow
Solution 1 - C#hyke20View Answer on Stackoverflow
Solution 2 - C#M.BabcockView Answer on Stackoverflow