Search code examples
c#asp.netxsltweb.config-transform

web.config file transformations


We release updates to our product several times a year and we need to be able to make changes to customer's web.configs.

We want to be able to apply these changes via c#.

Has anyone used the ctt.exe program and implemented a wrapper class for it? On initial tests it seems to strip all whitespace which isn't ideal.


Solution

  • Found the Microsoft.Web.XmlTransform library which resolves this perfectly without needing 3rd party tools.

    using Microsoft.Web.XmlTransform;
    

    ...

       using (XmlTransformableDocument document = new XmlTransformableDocument())
                    using (XmlTransformation transformation = new XmlTransformation(transformFilePath))
                    {
                        document.PreserveWhitespace = true;
                        document.Load(sourceFilePath);
    
                        var success = transformation.Apply(document);
                        if (!success)
                        {
                            string message = string.Format(
                                "There was an unknown error trying while trying to apply the transform. Source file='{0}',Transform='{1}', Destination='{2}'",
                                sourceFilePath, transformFilePath, destinationFilePath);
                            throw new Exception(message);
                        }
    
                        document.Save(destinationFilePath);
                    }