T4 append output to existing file

折月煮酒 提交于 2020-01-02 00:57:08

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/6261353/t4-append-output-to-existing-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!