我正在创建一个.tt
文件,将文本转换为模型类,进行练习。
使用所有.cs
生成models
文件,但我希望每个model
都保存在其自己的.cs
文件中的不同文件夹中。
实现这一目标的最佳方法是什么?
以下是如何从单个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);
}
#>