繁体   English   中英

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

[英]c# Visual Studio ...adding references programmatically

无论如何,可以以编程方式将引用添加到解决方案中吗?

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

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

获取环境

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

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

CodeProject上有一个示例。

该功能包含在单个类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");
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM