c#Visual Studio …以编程方式添加引用

无论如何,是否可以通过编程方式将参考添加到解决方案中?

我有一个加载项按钮,当用户按下它时,我想要添加一个引用。 这可能吗?

像这样的东西,我还没有测试过

得到环境

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

得到解决方案。

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

得到你想要的项目

 Project pProject = pSolution.Projects[0]; 

添加引用

 pProject.References.Add(string referenceFilePath); 

CodeProject上有一个例子。

该function包含在单个类elRefManager ,要调用的方法是CheckReferences 。 可以通过选择左侧的elRefManager.cs文件来查看代码。

正如你在文章中看到的那样……

 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"); } 

System.Assembly.load允许您调用库中未使用您的程序构建的函数。


如果要添加对项目的引用,以便在解决方案中可以使用以下内容。 与@Scots答案基本相同。

我在一个vb的宏中做到了,但我相信你可以得到这个想法

  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