8

使用 T4,我想根据检查相对于正在执行的模板文件的目录中的文件来生成一些代码。

c#中有没有办法识别当前模板文件的路径是什么?

4

1 回答 1

20
  • 您需要将指令的hostspecific="true"属性设置为.<#@ templateTrue
  • 这将使 T4 生成一个名为 的特殊属性Host,它使您可以访问ResolvePath方法和TemplateFile属性。
    • Host是类型ITextTemplatingEngineHost
    • TemplateFile是一个String通常是文件的文件系统路径的.tt- 但是其他 T4 主机(即除 Visual Studio 之外的主机)可能会在内存中加载 T4 文件,或者可能返回一些其他值,因为模板文件没有存在于磁盘上。
  • 您可以在此处找到详细信息:http ://www.olegsych.com/2008/02/t4-template-directive/

例如:

<#@ template hostspecific="true" #>
<#@ import namespace="System.IO" #>
<#@ import namespace="Microsoft.VisualStudio.TextTemplating" #>
<#
    ITextTemplatingEngineHost t4Host = this.Host;
    FileInfo t4FileInfo = new FileInfo( t4Host.TemplateFile );
#>

// This file generated by <#= t4FileInfo.FullName #>

于 2008-12-29T15:15:57.250 回答