Compartilhar via


How do I programmatically unload a project from a solution?

Happy new year everyone!  Here's my first technical post about the Visual Studio SDK :)

Back in December, I had a conference call with a potential partner who's building a custom integrated development environment on top of Visual Studio.

Once of the issues they ran into was trying to figure out how to unload a project from a solution.  They were looking for an easy way to do that but ended up with a hacky implementation.

I chatted with one of our developers (Ole) on the VS SDK team and he provided some sample code.

The code below can be copy-and-pasted into the menu command handler if you use the wizard to create a new VS Package with a new menu command.  Additionally, don't forget to add a reference to the EnvDTE assembly.

//Get the DTE object

            DTE dte = GetService(typeof(SDTE)) as DTE;

            Debug.Assert(dte != null);

            //Get the selected project

            Project selectedProject = null;

            if (dte.SelectedItems.Count > 0)

            {

                selectedProject = ((SelectedItem)dte.SelectedItems.Item(1)).Project;

            }

            if (selectedProject != null)

            {

                IVsSolution solutionService = GetService(typeof(SVsSolution)) as IVsSolution;

                Debug.Assert(solutionService != null);

                IVsHierarchy selectedHierarchy;

                ErrorHandler.ThrowOnFailure(solutionService.GetProjectOfUniqueName(selectedProject.UniqueName, out selectedHierarchy));

                Debug.Assert(selectedHierarchy != null);

                ErrorHandler.ThrowOnFailure(solutionService.CloseSolutionElement((uint)__VSSLNCLOSEOPTIONS.SLNCLOSEOPT_UnloadProject, selectedHierarchy, 0));

            }

Comments