I'm trying to create my first extension for visual studio and so far I've been following this tutorial to get me started (http://www.diaryofaninja.com/blog/2014/02/18/who-said-building-visual-studio-extensions-was-hard). Now I have a custom menu item appearing when I click on a file in the solution explorer. What I need now for my small project is to get the path of the file selected in the solution explorer but I can't understand how can I do that. Any help?
---------------------------- EDIT ------------------------------
As matze said, the answer is in the link I posted. I just didn't notice it when I wrote it. In the meanwhile I also found another possible answer in this thread: How to get the details of the selected item in solution explorer using vs package
where I found this code:
foreach (UIHierarchyItem selItem in selectedItems)
{
ProjectItem prjItem = selItem.Object as ProjectItem;
string filePath = prjItem.Properties.Item("FullPath").Value.ToString();
//System.Windows.Forms.MessageBox.Show(selItem.Name + filePath);
return filePath;
}
So, here are two ways to get the path to the selected file(s) :)
The article you mentioned already contains a solution for that.
Look for the menuCommand_BeforeQueryStatus
method in the sample code. It uses the IsSingleProjectItemSelection
method to obtain an IVsHierarchy
object representing the project as well as the id of the selected item. It seems that you can safely cast the hierarchy to IVsProject
and use it´s GetMkDocument
function to query the item´s fullpath...
IVsHierarchy hierarchy = null;
uint itemid = VSConstants.VSITEMID_NIL;
if (IsSingleProjectItemSelection(out hierarchy, out itemid))
{
IVsProject project;
if ((project = hierarchy as IVsProject) != null)
{
string itemFullPath = null;
project.GetMkDocument(itemid, out itemFullPath);
}
}
I don´t want to copy the entire code from the article into this answer, but it might be of interest how the IsSingleProjectItemSelection
function obtains the selected item; so I just add some notes instead which may guide into the right direction... The method uses the GetCurrentSelection
method of the global IVsMonitorSelection
service to query to the current selected item.