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