I want to save/run custom tools on a handful of .tt
files from my extension. I don't want to loop over all the files in the solution/project, rather I want to be able to use a relative (or full) path of the file to execute a save/run custom tool.
Is there a way to get a ProjectItem
object given a path of the file ($(SolutionDir)/MyProject/MyFile.tt
) so I can execute methods on it?
You can use the FindProjectItem
method of the EnvDTE.Solution
type to find a file within the current solution by its name. The ExecuteCommand
method is dependent on the current UI context; so the item must be selected, otherwise, the call fails.
private bool TryExecuteTextTemplate(string filename)
{
var dte = (DTE2)this.GetService(typeof(SDTE));
Solution solution = dte.Solution;
if ((solution != null) && solution.IsOpen)
{
VSProjectItem projectItem;
ProjectItem item = solution.FindProjectItem(filename);
if (item != null && ((projectItem = item.Object as VSProjectItem) != null))
{
// TODO: track the item in the Solution Explorer
try
{
projectItem.RunCustomTool();
return true;
}
catch (COMException)
{
}
}
}
return false;
}