c# Visual Studio …adding references programmatically

前端 未结 3 1884
生来不讨喜
生来不讨喜 2020-12-01 14:30

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. Is

相关标签:
3条回答
  • 2020-12-01 14:59

    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
    
    0 讨论(0)
  • 2020-12-01 15:18

    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");
    }
    
    0 讨论(0)
  • 2020-12-01 15:23

    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);
    
    0 讨论(0)
提交回复
热议问题