Search code examples
.netcode-generationt4t4-toolbox

T4 append output to existing file


Is it possible to make a T4 template output to be merged with an existing file?

For example, if a T4 template generates localization resource XML files, is it possible to merge them in some existing resource file?


Solution

  • You can get access to the underlying string builder the the T4 uses thought the GenerationEnvironment property. So by adding something like the following to your T4 you should be able to get a workable solution;

    <#@ template debug="false" hostspecific="false" language="C#" #>
    <#@ output extension=".txt" #>
    <#@ Import Namespace="System.IO" #>
    
    Line #<#= rand.Next(0, 100).ToString() #>
    <# AppendFile(@"C:\Development\PodCastSync\test\test.txt"); #>
    
    <#+
        Random rand = new Random();
    
        private void AppendFile(string filename)
        {
           File.AppendAllText(filename, GenerationEnvironment.ToString());
        }        
    #>
    

    If you want to stop the default backing file from getting updated you can set GenerationEnvironment to a new string builder after you save the contents to stop anything being output.