t4 generate file with no DependentUpon attribute in csproj file

筅森魡賤 提交于 2019-12-10 08:45:09

问题


We are using t4 templates for managing configurations in our project. And web.config file is generated via web.tt file. After generation in csproj file I have following:

<Content Include="Web.config">
  <AutoGen>True</AutoGen>
  <DesignTime>True</DesignTime>
  <DependentUpon>Web.tt</DependentUpon>
</Content>

Is it possible to configure t4 template somehow to generate independent web.config file, not under web.tt?


回答1:


Yes you can. First define a save routine in a T4 include file.

SaveOutput.tt:

<#@ template language=“C#” hostspecific=“true” #>
<#@ import namespace=“System.IO” #>
<#+
  void SaveOutput(string fileName)
  {
      string templateDirectory = Path.GetDirectoryName(Host.TemplateFile);
      string outputFilePath = Path.Combine(templateDirectory, fileName);
      File.WriteAllText(outputFilePath, this.GenerationEnvironment.ToString()); 

      this.GenerationEnvironment.Remove(0, this.GenerationEnvironment.Length);
  }
#>

Now every time you call SaveOutput with a file name it will write the current buffer to that external file. For example.

Web.tt:

<#@ include file=“SaveOutput.tt” #>
<#
    GenerateConfig();
    SaveOutput(”..\..\Web.Config”);  
#>

If you want to generate multiple files:

<#@ include file=“SaveOutput.tt” #>
<#
    GenerateFile1();
    SaveOutput(”..\..\File1.txt”);  

    GenerateFile2();
    SaveOutput(”..\..\File2.txt”); 
#>


来源:https://stackoverflow.com/questions/6980215/t4-generate-file-with-no-dependentupon-attribute-in-csproj-file

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