How to create a solution folder inside another solution folder

Today I have received an e-mail asking if there is a workaround to the problem that I explained in the post PRB: NotImplementedException adding a solution folder to a solution folder in Visual Studio from a macro or add-in.

I hadn’t updated the post yet until today but I already hinted the solution in this other post: HOWTO: Create a project from a Visual Studio add-in inside a solution folder

The trick is to cast the EnvDTE.Project.Object property to the EnvDTE80.SolutionFolder type introduced by VS 2005.

Here it is a sample code:

Sub AddNestedFoldersToSolution()

   Dim sol2 As EnvDTE80.Solution2
   Dim solFolderProject1 As EnvDTE.Project
   Dim solFolderProject2 As EnvDTE.Project
   Dim solFolder As EnvDTE80.SolutionFolder

   sol2 = CType(DTE.Solution, EnvDTE80.Solution2)

   solFolderProject1 = sol2.AddSolutionFolder("Folder 1")

   solFolder = CType(solFolderProject1.Object, EnvDTE80.SolutionFolder)

   solFolderProject2 = solFolder.AddSolutionFolder("Folder 2")

End Sub