C# Programming > Miscellaneous

Transform .NET Config Files
Programmatically

 

.NET Config Files

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?

Transformation Project

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.

Transform Programmatically

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.

  • First of all, we must know where msbuild.exe is, which is not too big of a deal since .NET Framework 4.0 is required we can use the default installation path.
  • Second is the fact that msbuild requires an actual project file (not a string in memory). We solve this by creating a temporary file for both the project file and the output file.
  • Finally the /t:Transform part just tells msbuild to run the Transform step from our project. You can name this anything, "Transform" just makes sense.

Source Code

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.

Back to C# Article List