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? Continue reading

Add A Namespace Import Via Visual Studio Automation

Suppose you had a code document represented by a FileCodeModel object. And suppose you were modifying the containing DOM. Sometimes, you might need to add a namespace import to the document (i.e. “using …” in C# of “Import …” in VB). A namespace import is represented by the CodeImport interface. Reading out the namespace imports is easy:

var imports = fileCodeModel.CodeElements.OfType<CodeImport>();

But how do you add a new CodeImport element? Well, TIL that it’s worthwhile to look at all versions of an automation interface (e.g. FileCodeModel2 instead of just FileCodeModel). Sometimes, you might find just the method you were looking for 🙂 So the answer to the question in this case is:

var fileCodeModel = (FileCodeModel2)projectItem.FileCodeModel;
fileCodeModel.AddImport("My.New.Namespace");