Adding Solution Folders Via Visual Studio Automation

In the Visual Studio Solution Explorer, you can add solution folders to group projects or project items. These solution folders do not represent folders in the file system but are merely virtual. Adding these folders in the Solution Explorer is a trivial task, but how do you do that in code via EnvDTE?

Once you got the DTE instance, you can get its Solution property. This is cool, but the Solution interface has no methods to add a solution folder. You’ll need to cast is to Solution2. Then you can call its AddSolutionFolder method. Consider the following code:

// get the automation root object from somewhere
DTE dte = ... 

// get the current solution
var solution = dte.Solution;

// add a solution folder
var folder = solution.AddSolutionFolder("myfolder");

Good stuff. But if you look closely (in the code editor or in the documentation), you’ll notice that AddSolutionFolder() returns a Project interface!

Well, that’s not very helpful, is it? You might be able to add single files (aka ProjectItems), but what about projects? What if you wanted to organize projects in solution folders? You cannot nest projects in projects, so what do? To do that, we’ll rewrite the code from above:


// get the automation root object from somewhere
DTE dte = ... 

// get the current solution
var solution = dte.Solution;

// add a solution folder
var folderProject = solution.AddSolutionFolder("myfolder");
var folder = (SolutionFolder)folderProject.Object;

// add any existing projects to the folder
folder.AddFromFile(@"c:\mycoolproject\mycoolproject.csproj");

So the trick is to get a SolutionFolder instance from the project’s Object property. But what is the Object property for, anyway? The MSDN documentation states:

Gets an interface or object that can be accessed by name at run time.

And that’s about all the documentation on the property – and to be honest, it didn’t help me understand what it’S for at all. After some research, I now understand that the Object property returns whatever object the Porject really is. It might return a SolutionFolder, a VSProject, a VCProject, a VSWebSite or whatever interface suits best at runtime.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s