将T4生成的代码写入单独的输出文件

问题描述 投票:0回答:1

我正在创建一个.tt文件,将文本转换为模型类,进行练习。

使用所有.cs生成models文件,但我希望每个model都保存在其自己的.cs文件中的不同文件夹中。

实现这一目标的最佳方法是什么?

c# .net templates transformation t4
1个回答
1
投票

以下是如何从单个T4模板输出多个文件的简单示例。

使用SaveOutput-method输出文件(Content1.txt,Content2.txt ..)被创建到与.tt文件相同的文件夹,SaveOutputToSubFolder输出文件转到单独的文件夹(1 \ Content1.txt,2 \ Content2.txt .. )

<#@ template debug="false" hostspecific="true" language="C#" #>
<#@ assembly name="System.Core" #>
<#@ import namespace="System" #>
<#@ import namespace="System.IO" #>
<#@ output extension=".txt" #>
<#
for (Int32 i = 0; i < 10; ++i) {
#>
File Content <#= i #>
<#

  SaveOutput("Content" + i.ToString() + ".txt");
  //Uncomment following to write to separate folder 1,2,3
  //SaveOutputToSubFolder(i.ToString(),"Content" + i.ToString() + ".txt");
}
#>
<#+
private void SaveOutput(string outputFileName) {
  string templateDirectory = Path.GetDirectoryName(Host.TemplateFile);
  string outputFilePath = Path.Combine(templateDirectory, outputFileName);
  File.WriteAllText(outputFilePath, this.GenerationEnvironment.ToString()); 
  this.GenerationEnvironment.Remove(0, this.GenerationEnvironment.Length);
}
private void SaveOutputToSubFolder(string folderName, string outputFileName) {
  string templateDirectory = Path.GetDirectoryName(Host.TemplateFile);
  string newDirectoryName = Path.Combine(templateDirectory,folderName);
  if(!Directory.Exists(newDirectoryName))
    Directory.CreateDirectory(newDirectoryName);
  string outputFilePath = Path.Combine(newDirectoryName, outputFileName);
  File.WriteAllText(outputFilePath, this.GenerationEnvironment.ToString()); 
  this.GenerationEnvironment.Remove(0, this.GenerationEnvironment.Length);
}
#>
© www.soinside.com 2019 - 2024. All rights reserved.