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");

Freelance full-stack .NET and JS developer and architect. Located near Cologne, Germany.

Leave a Reply

Your email address will not be published. Required fields are marked *