Write T4 generated code to separate output files

☆樱花仙子☆ 提交于 2019-12-08 10:08:30

问题


I am creating a .tt file that transforms text into model classes, to practice.

A .cs file is generated that with all models, but I would like each model to be saved in its own .cs file in a different folder.

What would be the best approach to achieve this?


回答1:


Here is simple example how you can output multiple files from single T4 template.

Using SaveOutput-method output files (Content1.txt,Content2.txt..) are created to same folder than .tt-file, with SaveOutputToSubFolder output files goes to separate folders (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);
}
#>


来源:https://stackoverflow.com/questions/55296544/write-t4-generated-code-to-separate-output-files

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