49

How can I get a reference to the directory of the visual studio project or solution or the directory of the t4 template from within a t4 template?

I have a template that concatenates a number of files together which are located relative to the template. I need to get a reference to there absolute location through a relative means. Hard coding an absolute path is not acceptable because the visual studio project will not always be in the same location and this would break the code generation. Reading the current working directory from the environment doesn't work either because that returns the location of where the T4 engine lives not the template. I'm just getting in to t4 so any help would be appreciated.

2 Answers 2

91

See The Host Specific Parameter section HERE.

This snippet shows how to get the full path of src relative to the template.

<#@ template hostspecific="true" #>
// The location of the src folder relative to the t4 template:
// <#= Host.ResolvePath("src") #>
0
5

You can grab the path like this aswell

<#@ template hostspecific="true" #>
<#= Path.GetDirectoryName(this.Host.TemplateFile) #>
1
  • 3
    importing namespace of Path is needed too: <#@ import namespace="System.IO" #> May 9, 2020 at 13:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.