2011-02-10 118 views
16

我在Visual Studio 2010中使用T4,我想遍歷解決方案中的文件,但是我發現T4源代碼在一種沙箱中工作,並且當前工作目錄位於程序文件的Visual Studio 10目錄中。T4獲取當前解決方案的工作目錄

有沒有辦法引用T4文件相對論的解決方案,以便它不會破壞構建,或者在一個沒有相同文件結構的其他框中工作等?

感謝

回答

26

必須將hostspecific屬性設置爲true,像這樣:

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

ITextTemplatingEngineHost界面會給你你需要的信息。

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

我不相信有參考的解決方案的一種方式,但你可以在你的*.tt文件,並從那裏得到其他文件的路徑。

要加載相對於文本模板的位置的文件,您可以使用此:

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

謝謝Shiv!我最終使用this.Host.TemplateFile,它直接指向模板並從那裏運行。 – aceinthehole 2011-02-17 17:19:49

9

這是我用得到解決基本目錄的方法:

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); 
} 
4

這裏的如何使用創建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 version="1.0" encoding="utf-8"?> 
<configuration> 
    <mySetting filePath="<#= solutionDirectory #>\MySubfolder\MyFile.exe" /> 
</configuration> 

XML att ribute「filePath」將等於Visual Studio的解決方案目錄加上「\ MySubfolder \ MyFile.exe」。

相關問題