T4 append output to existing file
Asked Answered
C

1

12

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?

Carlocarload answered 7/6, 2011 at 6:28 Comment(0)
O
13

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.

Octane answered 8/6, 2011 at 11:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.