T4 Get Current Working Directory of Solution

前端 未结 3 1076
慢半拍i
慢半拍i 2021-02-01 06:20

I am using T4 in Visual Studio 2010, and I want to iterate over the files in my solution, however I have found that T4 source generation works in a kind of a sandbox, and the cu

相关标签:
3条回答
  • 2021-02-01 06:48

    Here's the how to use the logic JCallico provided in a T4 template that creates an XML file:

    <#@ 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>
    

    The XML attribute "filePath" will equal the Visual Studio's solution directory plus "\MySubfolder\MyFile.exe".

    0 讨论(0)
  • 2021-02-01 06:50

    You must set the hostspecific attribute to true like so:

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

    The ITextTemplatingEngineHost interface will give you the information you need.

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

    I don't believe there is a way to reference the solution, but you can get the path in which your *.tt file is and from there get other files.

    To load a file from a location relative to the text template, you can use this:

    this.Host.ResolvePath("relative/path.txt")
    
    0 讨论(0)
  • 2021-02-01 06:53

    This is the method I use to get the solution base directory:

    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);
    }
    
    0 讨论(0)
提交回复
热议问题