Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 900
Sly Avatar asked Jun 07 '11 06:06

Sly


1 Answers

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.

like image 180
squig Avatar answered Oct 22 '22 02:10

squig