Search code examples
c#.netvisual-studiot4texttemplate

T4 Get Execution File Name of Current Solution


I'm using T4 text template to generate a C# class for use in any c# projects. But, now I need to know the target project execution file name, then to know that config file name and ...

For this job I tried to blow codes, but I think is not stable for all projects.

<#@ template language="C#" debug="false" hostspecific="true" #>
<#@ assembly name="EnvDTE" #>
<#@ import namespace="EnvDTE" #>
<#@ output extension=".cs" #>

<# 
 IServiceProvider serviceProvider = (IServiceProvider)this.Host;
 var dte = serviceProvider.GetService(typeof(DTE)) as DTE;  
 var solutionsPath = Host.ResolveAssemblyReference("$(SolutionDir)"); 
 var projectItem = dte.Solution.FindProjectItem(Host.TemplateFile);
 var vsProject = projectItem.ContainingProject; 
#>

1.<#= System.IO.Path.GetFileName(dte.Solution.FullName) #>
2.<#= solutionsPath  #>
3.<#= this.Host.ResolveParameterValue("-", "-", "projects") #>
4.<#= dte.Solution.FullName #>
5.<#= vsProject.Name #>

Result is:

1.ProjectName.sln
2.D:\MyProject\SolutionDirectory\src\
3.ProjectName1|ProjectName2|ProjectName3
4.D:\MyProject\SolutionDirectory\src\ProjectName.sln
5.ProjectName

Please help me to find a stable and safe way to get current project execution file name, for example: projectname.exe or $(TargetFileName)


Solution

  • Try this:

    ProjectItem projItem = dte.Solution.FindProjectItem(Host.TemplateFile);
    Project prj = projItem.ContainingProject;
    string outputFileName = prj.Properties.Item("OutputFileName").Value.ToString();