How to insert <configSections> as first child in app.config

808 views Asked by At

I'm currently authoring a new NuGet package, but I can't get the app.config.install.xdt file right (which is the xml file that transforms app.config to suit the installed package).

The problem is inserting a <configSections> section in app.config as the first child - but only in case it is missing!

It MUST be the first child, or the application will fail with an exception (Microsoft enforcement).

If I just use the regular “InsertIfMissing” transform, the insertion takes place after any existing children, so that seems a no-go.

What can I do to solve my problem?

3

There are 3 answers

1
Leo Liu On

How to insert as first child in app.config

You can utilize the attribute xdt:Transform="InsertBefore" to insert a new element in the section but before the any other element, like:

<configSections xdt:Transform="InsertBefore(/configuration/*[1])" />

Certificate: XDT Transform: InsertBefore - Locator Condition is ignored

And see How to use XDT in NuGet - Examples and Facts for some more details.

Hope this helps.

1
pkd3vv On

I was looking for the solution as well...

<configSections xdt:Transform="Remove" />
<configSections xdt:Transform="InsertBefore(/configuration/*[1])">
1
Evert Timmer On

I've had exactly the same problem and solved it this way:

<configSections xdt:Transform="InsertBefore(/configuration/*[1])" />
<configSections xdt:Locator="XPath(/configuration/configSections[last()])">
     do_your_stuff_with_sections_here...
</configSections>
<configSections xdt:Transform="RemoveAll" xdt:Locator="Condition(count(*)=0)" />

The first line unconditionally creates the node as first child:

<configSections xdt:Transform="InsertBefore(/configuration/*[1])" />

The second line makes sure all your edits are done to the last configSections node, which is de correct node if it already existed…

<configSections xdt:Locator="XPath(/configuration/configSections[last()])">

After the transforms you do in de configSections block, you enter a command that removes all empty configSections nodes… (last line)

<configSections xdt:Transform="RemoveAll" xdt:Locator="Condition(count(*)=0)" />