Skip to content

Instantly share code, notes, and snippets.

@leandroribeiro
Last active February 10, 2017 18:47
Show Gist options
  • Save leandroribeiro/258e28f9384357708c80b85859b6081a to your computer and use it in GitHub Desktop.
Save leandroribeiro/258e28f9384357708c80b85859b6081a to your computer and use it in GitHub Desktop.
Transform web.config on build with custom targets
<!-- More read here: https://msdn.microsoft.com/en-us/library/ms366724.aspx -->
<!-- First, we extend the "BuildDependsOn" property with our custom target for applying the transform.
This is a cleaner/safer alternative to overloading the "AfterBuild" target: -->
<PropertyGroup>
<BuildDependsOn>
$(BuildDependsOn);
_VisualStudioApplyTransform;
</BuildDependsOn>
</PropertyGroup>
<!-- Now, down to business: this is our target for applying the config transform.
I've included some conditions, to help avoid the build from blowing up when a transform
doesn't exist for the current configuration: -->
<Target Name="_VisualStudioApplyTransform">
<!-- Transform the file out to a temp file, sourcing from our Web.config file: -->
<TransformXml
Source="Web.config"
Transform="Web.$(Configuration).config"
Destination="Web.config.temp"
Condition="Exists('Web.$(Configuration).config')" />
<!-- Copy the temp file, back over the top of Web.config, the file handle opened by TransformXml is closed now: -->
<Copy
SourceFiles="Web.config.temp"
DestinationFiles="Web.config"
Condition="Exists('Web.config.temp')" />
<!-- Cleanup after ourselves: -->
<Delete
Files="Web.config.temp"
Condition="Exists('Web.config.temp')" />
</Target>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment