Update (or Delete) an entry from appSettings in web.config using MSBuild and the XmlUpdate task

by Oliver 11. May 2016 12:24

How do I modify an entry in the appSettings node during deployment?

We use a custom MSBuild script to deploy our discoverize portals and wanted to set a portal dependent key, namely NewRelic.AppName. So how did we do it? We use the XmlUpdate task from the MSBuild Community Tasks project. Here's the code:

  1. <!-- Import all MSBuild Community Tasks -->
  2. <Import Project="$(LibFolder)\msbuild\MSBuild.Community.Tasks.Targets" />
  3.  
  4. <!-- Define the property value we want to use below -->
  5. <PropertyGroup>
  6.   <NewRelicAppName>$([System.IO.Path]::GetFileName($(Destination))), Discoverize Portals</NewRelicAppName>
  7. </PropertyGroup>
  8.  
  9. <!-- Update NewRelic.AppName key in appSettings of web.config -->
  10. <XmlUpdate XmlFileName="$(Destination)\web.config"
  11.   XPath="/configuration/appSettings/add[@key='NewRelic.AppName']/@value"
  12.   Value="$(NewRelicAppName)" />

I'm no XPath guru, so I was glad to find this thread that contained the XPath expression needed to select a certain appSettings entry by key and update its value.

If you seek to delete an element from an XML file, this stackoverflow answer taught me that there is also a Delete attribute on the XmlUpdate task :-)

Happy deploying!

Comments are closed

About Oliver

shades-of-orange.com code blog logo I build web applications using ASP.NET and have a passion for javascript. Enjoy MVC 4 and Orchard CMS, and I do TDD whenever I can. I like clean code. Love to spend time with my wife and our children. My profile on Stack Exchange, a network of free, community-driven Q&A sites

About Anton

shades-of-orange.com code blog logo I'm a software developer at teamaton. I code in C# and work with MVC, Orchard, SpecFlow, Coypu and NHibernate. I enjoy beach volleyball, board games and Coke.