c# Visual Studio ...adding references programmatically

Is there anyway that a reference can be added to a solution programmatically?

I have an add-in button, when the user presses it, I want a reference to be added.

The reason is, I have created a piece of software that I want to be integrated into any given VS program (if the developer wants it), they would simply click the add-in button and the reference would be loaded in the current solution.

Is this possible?


Solution 1:

Something like this I haven't tested it

get the environment

EnvDTE80.DTE2 pEnv = null;
Type myType = Type.GetTypeFromProgID("VisualStudio.DTE.8.0");          
pEnv = (EnvDTE80.DTE2)Activator.CreateInstance(myType, true);

get the solution.

Solution2 pSolution = (Solution2)pEnv.VS.Solution;

get the project that you want

Project pProject = pSolution.Projects[0];

add the reference

pProject.References.Add(string referenceFilePath);

Solution 2:

There is an example on CodeProject.

The functionality is contained within a single class elRefManager and the method to call is CheckReferences. The code can be looked at here by selecting the elRefManager.cs file on the left hand side.

As seen in the article you could do...

private void button1_Click(object sender, System.EventArgs e)
{
    int ec;
    ec=elRefManager.CheckReferences(null, new string[] {textBox1.Text});

    if (ec<0)
        MessageBox.Show("An error occurred adding this reference");
    if (ec>0)
        MessageBox.Show("Could not add " + textBox1.Text + 
                    "\nCheck its spelling and try again");
}

Solution 3:

System.Assembly.load Allows you to call functions in a library that were not built with your program.


If you want to add a reference to the project so that its in the solution you can use the following. Basically the same as @Scots answer.

I did it in a macro which is vb but I'm sure you can get the idea

    DTE.Windows.Item(Constants.vsWindowKindSolutionExplorer).Activate()
    Dim objProject As EnvDTE.Project
    Dim i As Long
    i = DTE.Solution.Projects.Count
    For Each objProject In DTE.Solution.Projects
        If (objProject.Name() = "csCA") Then
            Dim vsproj As VSLangProj.VSProject
            vsproj = objProject.Object
            vsproj.References.Add("C:\Users\test.dll")
        End If
    Next