Search code examples
visual-studioenvdte

How to programatically add an existing project to a solution folder in Visual Studio


I have a solution that I want to programatically add an existing project to.

Opening the solution using envdte automation is relatively easy

        var envDteType = Type.GetTypeFromProgID("VisualStudio.DTE.15.0");

        var envDte = Activator.CreateInstance(envDteType, true);
        var dte2 = (DTE2)envDte;

        var solution = (Solution4)dte2.Solution;
        solution.Open(filename);

But adding an existing project to a solution folder is not.

Note this isn't using a template which is what most google results give

Using

var referencesFolder = solution.AddSolutionFolder("References");
referencesFolder.ProjectItems.AddFromFile(fullPathToCsProj);

Adds the project file as a plain old file, not a CSharp project.

The use case is we are in nuget update hell with our library management and will dereference nuget and add a direct project reference instead. There are around 55 projects that require hundreds of dereferences hence the automation.


Solution

  • The trick is to add cast the returned project to a SolutionFolder (note the .Object)

    var referencesFolder = (SolutionFolder) solution
                                      .AddSolutionFolder("References")
                                      .Object;
    
    referencesFolder.AddFromFile(fullPathToCsProj);
    

    This gives access to AddFromFile on the root entity which adds the project properly