How to open a file on relative path using T4?
Asked Answered
G

2

12

I'm trying to run a T4 template that opens a XML file and uses it contents to generate a code artifact. However, I'm getting the an error message when I try to run a T4 template similar to the one below

<#@ template debug="false" hostspecific="false" language="C#" #>
<#@ assembly name="System.Xml.dll" #>
<#@ assembly name="System.Xml.Linq.dll" #>
<#@ import namespace="System.IO" #>
<#@ import namespace="System.Xml" #>
<#@ import namespace="System.Xml.Linq" #>
<#@ output extension=".cs" #>
namespace ConsoleApplication1
{
<# XElement fragment = XElement.Load("data.xml"); #>
...

Visual Studio 2010 error list is showing the following message

Running transformation: System.IO.FileNotFoundException: Could not find file 'C:\Program Files\Microsoft Visual Studio 10.0\Common7\IDE\data.xml'.

It is trying to open the file on the path where the TextTemplateFileGenerator custom tool runs. I'd like it to open the file relative to my project path, because other developers on my team use different folder structures. Does anyone know if it is something possible to accomplish?

Gustatory answered 28/5, 2010 at 19:35 Comment(0)
Z
23

Change hostspecific option in template directive to "true" and call Host.ResolvePath("data.xml").

Zitella answered 28/5, 2010 at 19:43 Comment(2)
For what it's worth, this is documented here: msdn.microsoft.com/en-us/library/bb126478.aspxSnipes
Thus: string myFile = File.ReadAllText(this.Host.ResolvePath("MyFile.txt"));Devries
P
0

I had a similar problem but Host.ResolvePath didn't work for me because my relative path contained "..\.." in it. I worked around it by doing this:

string ttpath = this.Host.TemplateFile;
string resolvedPath = Path.GetFullPath(Path.GetDirectoryName(ttpath) + @"..\..\<Path To File>");
Pris answered 12/8, 2016 at 16:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.