How to get a ProjectItem by its full path?
- Hi.
I need to get a project item by its full path e.g. "C:\MyProject\MyClass.cs" for files and "C:\MyProject\MyFolder" for folders. I know about the FindProjectItem method of the Solution interface. It doesn't work for me because it returns the first ProjectItem in the solution that has the given path. And I guess there may be more than one references to that file. I need to only search in a single project and either get the ProjectItem or get null if the item is not found.
Is it, of course, possible to traverse all ProjectItems in the project, get each item's filename and comapre it to the one I am looking for. Is there any other way(without manually enumerating and doing string comparison - it seems kind of slow for big projects)?
Thanks.
Answers
- Hello,
AFAIK, no. You have to traverse the projectitems of the project.
MZ-Tools: Productivity add-ins for Visual Studio: http://www.mztools.com. My blog about VS extensibility: http://msmvps.com/blogs/carlosq/- Marked As Answer byLyubomir Dokov Wednesday, November 04, 2009 5:07 AM
All Replies
- Hello,
AFAIK, no. You have to traverse the projectitems of the project.
MZ-Tools: Productivity add-ins for Visual Studio: http://www.mztools.com. My blog about VS extensibility: http://msmvps.com/blogs/carlosq/- Marked As Answer byLyubomir Dokov Wednesday, November 04, 2009 5:07 AM
- Traverse it is, then.
Thanks for your reply. Okay, there is a problem with the traverse solution. It works fine if I search for a file or a folder. However, if I want to search for a linked item (added using "Add as Link" option), there is a problem.
Consider the following scenario: I subscribe for the OnQueryRemoveFiles event (implementing the IVsTrackProjectDocumentsEvents2 interface). One of its parameters is a string array containing the paths of the files that are to be removed. If a file is a link, its element in this array is the absolute path to the source file. So there is no way to get its ProjectItem object because I don't know where in the project the file is located(which project folder).
Well, there is an "extended traverse" solution, where I search in all folders until I find an item with the same name, then check if it is a link to the file I look for. But this sounds slow...Any ideas?
- The ProjectItem has properties such as "IsLink" (IIRC), etc. that allows you to determine if the file name, path, parent project, is link or not, etc. so you can use a traversal approach. If this is slow or not depends on the number of files/projects in the solution, and on the code that you use, but AFAIK there is no other way...
MZ-Tools: Productivity add-ins for Visual Studio: http://www.mztools.com. My blog about VS extensibility: http://msmvps.com/blogs/carlosq/ - Traverse it is, then. Again. :)
It is fast enough on projects I test with, I hope it is OK on bigger projects as well.


