T4获取解决方案的当前工作目录

我在Visual Studio 2010中使用T4,我想在我的解决方案中迭代文件,但是我发现T4源代码生成在一种沙箱中,当前工作目录在Visual Studio 10目录中在程序文件中。

有没有办法相对地引用T4文件的解决方案,以便它不会破坏构建,或者在没有相同文件结构的其他人的框中工作?

谢谢

您必须将hostspecific属性设置为true,如下所示:

 <#@ template language="C#" hostspecific="True" #> 

ITextTemplatingEngineHost界面将为您提供所需的信息。

 <#= this.Host.ResolveParameterValue("-", "-", "projects") #> 

我不相信有一种方法可以引用该解决方案,但是您可以获得*.tt文件所在的路径,并从那里获取其他文件。

要从相对于文本模板的位置加载文件,您可以使用:

 this.Host.ResolvePath("relative/path.txt") 

这是我用来获取解决方案基目录的方法:

 public string GetSolutionDirectory() { var serviceProvider = this.Host as IServiceProvider; var dte = serviceProvider.GetService(typeof(EnvDTE.DTE)) as EnvDTE.DTE; return System.IO.Path.GetDirectoryName(dte.Solution.FullName); } 

以下是如何使用创建XML文件的T4模板中提供的逻辑JCallico:

 <#@ template debug="false" hostspecific="true" language="C#" #><# /* hostspecific must be set to "true" in order to access Visual Studio project properties. */ #> <#@ assembly name="System.Core" #> <#@ import namespace="System.Text" #> <#@ output extension=".xml" #> <#@ assembly name="EnvDTE" #><# /* This assembly provides access to Visual Studio project properties. */ #> <# var serviceProvider = this.Host as IServiceProvider; var dte = serviceProvider.GetService(typeof(EnvDTE.DTE)) as EnvDTE.DTE; var solutionDirectory = System.IO.Path.GetDirectoryName(dte.Solution.FullName); #>     

XML属性“filePath”将等于Visual Studio的解决方案目录以及“\ MySubfolder \ MyFile.exe”。