t4生成csproj文件中没有DependentUpon属性的文件

时间:2011-08-08 09:39:20

标签: .net visual-studio t4

我们正在使用t4模板来管理项目中的配置。 web.config文件是通过web.tt文件生成的。在csproj文件中生成后,我有以下内容:

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

是否可以以某种方式配置t4模板以生成独立的web.config文件,而不是在web.tt下?

Web.config file depends upon web.tt

1 个答案:

答案 0 :(得分:3)

是的,你可以。首先在T4包含文件中定义一个保存例程。

<强> 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);
  }
#>

现在每次使用文件名调用SaveOutput时,它都会将当前缓冲区写入该外部文件。例如。

<强> Web.tt

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

如果要生成多个文件:

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

    GenerateFile2();
    SaveOutput(”..\..\File2.txt”); 
#>
相关问题