Wednesday, January 24, 2007

How to get the containing folder for a ProjectItem in a Visual Studio 2005 designer

It was a long search, and I must say that the item in question was very well hidden (congratulations to whoever put it there :)). The problem was this: how do you, from inside a Visual Studio designer or add-in, get a reference to the current ProjectItem's containing folder? And I don't mean the folder on the disk, but the Visual Studio project folder that may not be the same.

You'd never find it... It's in ProjectItem.Collection.Parent! Here's some sample code (the idea is to put the code into a component designer: I haven't tried this actual code, but the basic idea is the same as what worked for me):

public ProjectItem FindActiveDocumentsSibling(string fileName)
{
// we need the DTE to get the active document
DTE dte = (DTE)Component.Site.GetService(typeof(DTE));

Project ret = null;

// try-catch is necessary because Item() throws an exception if no item is found
try
{
((ProjectItem)dte.ActiveDocument.ProjectItem
.Collection.Parent).ProjectItems.Item(fileName);
}
catch { }

return ret;
}


So, what's this for? Well, I'm trying to put an NHibernate *.hbm.xml file next to a code class. (Look at a previous post as to why it isn't a child item but a sibling). Now if I could only figure out how to (or whether I should) open it using Visual Studio mechanisms - but without showing it to the user...

1 comment:

Frank Wisniewski said...

Bravo Sir, you truly are a gentlemen! You just saved me so much time, thank you so much. Send me an email and I will send you a free license for my vs extension product T4 Awesome(www.t4awesome.com) as thanks.