wolfgang ziegler


„make stuff and blog about it“

Using Relative Paths in T4 Templates

December 21, 2014

If you’re using T4 Code Generation, it’s a quite common scenario to have an external data source (e.g. XML, JSON, …) from which your actual code gets generated. To be able to locate these external files as flexible as possible, relative paths come in handy.

Unfortunately, these won’t work out of the box since your are getting paths relative to the actual templating executable TextTransform.exe and not to your current project.

Luckily, a couple of extra lines of code will provide you with the correct relative paths.

  • Set the hostspecific attribute to true
<#@ template debug="false" hostspecific="true" language="C#" #>
  • Import the System.IO namespace
<#@ import namespace="System.IO" #>
  • Use Host.ResolvePath on an empty string to get the current directory and combine it with your relative path.
var currentPath = Host.ResolvePath(string.Empty);
var relativePath = Path.Combine(currentPath , @"..\..\data.xml"));
Done!