Search code examples
visual-studio-2010visual-studioautomationenvdtecsproj

How to add a reference to another project in my solution through Visual Studio automation


I create a new solution and add some projects to it via the Solution2.AddFromTemplate. Now before I can build my solution successfully, I need to add a project reference from one of the projects to the other. I'm trying to navigate the VS automation object model, but cannot find how to do this.

I realize that I could just open the csproj as XML and change it on disk (as suggested here), but then I need to handle Visual Studio detecting the project file changing and prompting to reload it.

Anyone know how to do this or point me in the right direction?


Solution

  • Found the answer, posting for future reference.

    The trick is to cast the Object property of the EnvDTE.Project to VSProject and then call AddProject on its References property.

    var targetProject = (VSProject) _project.Object;
    targetProject.References.AddProject(sourceProject);