C# Programming > Miscellaneous
A great feature introduced in .NET Framework 4.0 was the ability to transform .net configuration files, particularly web.config files. This allows you to have a main file and have transformation files for different environments. So for example you might have the files Web.config, Web.Dev.config, Web.Testing.config, Web.Production.config.
These transformation files are applied to the original configuration file during the build processes depending on the build target. But what about triggering this process programmatically, outside of a build process?
To transform web.config files programmatically we are going to trigger a miniature build that will include only the config transformation step. Note that this requires .NET Framework 4.0 and up. I have shamelessly borrowed the project from this awesome blog and adapted it to our purpose:
<Project ToolsVersion="4.0" DefaultTargets="Demo" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <UsingTask TaskName="TransformXml" AssemblyFile="$(MSBuildExtensionsPath)\Microsoft\VisualStudio\v10.0\Web\Microsoft.Web.Publishing.Tasks.dll"/> <Target Name="Transform"> <TransformXml Source="{source}" Transform="{transform}" Destination="{output}"/> </Target> </Project>
I modified it only to allow replacing the source, transform, and destination attributes later. We will bundle this project along with our C# code. We can either make it a constant string or we can add it as an embedded resource.
So how do we trigger the transformation project programmatically? Easy, we just call msbuild with this command:
msbuild [project path] /t:Transform
There are a few things to keep in mind.
The source code implements the approach outlined above and wraps it in a neat static function. You can use it to programmatically transform config files like this:
string configFile = "Web.Config"; string transformFile ="Web.Production.Config"; string transformedContent = ConfigTransform.Transform(configFile, transformFile);
Notice that it returns the content of the transformed file. Feel free to modify it to return a file path, or to accept content as parameters instead of files paths.
As promised, below is the code.