Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 462
Darren Young Avatar asked Dec 10 '10 15:12

Darren Young


People also ask

What is the full name of C?

In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr.

What is C programming used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

Why is C named so?

Quote from wikipedia: "A successor to the programming language B, C was originally developed at Bell Labs by Dennis Ritchie between 1972 and 1973 to construct utilities running on Unix." The creators want that everyone "see" his language. So he named it "C".


2 Answers

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);
like image 163
scott Avatar answered Sep 20 '22 07:09

scott


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");
}
like image 35
Aaron McIver Avatar answered Sep 22 '22 07:09

Aaron McIver