在同一个解决方案中动态地将项目的引用添加到另一个项目

11

我有一个解决方案,其中包含三个动态创建的项目。现在我需要将第一个项目的引用添加到第二个和第三个项目中。当我尝试这个逻辑时,我能够单独构建项目,但是在构建解决方案时,它会抛出"Reference could not be loaded properly"错误。这是直接使用theVSProject.References.Add()方法添加.dll时发生的。

所以我尝试使用下面的代码作为解决方案,但仍然遇到一些错误。

Imports VSLangProj
' Add the second project as a reference to the first project.
Sub AddProjectExample()
   ' First project is a Visual Basic or C# project.
   Dim theVSProject As VSProject = _
      CType(DTE.Solution.Projects.Item(1).Object, VSProject)

   ' Second project is any type of project.
   Dim secondProject As Project = DTE.Solution.Projects.Item(2)

   ' AddProject returns the newly created Reference object.
   Dim newReference As Reference
   newReference = theVSProject.References.AddProject(secondProject)
End Sub

错误是,

The referenced assembly 'EnvDTE, Version=7.0.3300.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' could not be found. 

有解决方案吗?

我们没有权限访问 VS IDE 文件夹来应用以下修复方法。

注意: 我们也尝试了以下应用于 App.Config 的解决方案,但问题仍然存在。

msdn


2
你能通过编程的方式修改项目文件吗? - NWard
3
请问您能否在项目文件的适当<ItemGroup>元素中添加另一个<ProjectReference ...>元素?您可以包括编译后.dll文件的路径、项目GUID和名称。例如:<ProjectReference Include="..\[project]\[projectName].csproj"> <Project>{[projectGuid]}</Project> <Name>[projectName]</Name> </ProjectReference> - NWard
你可以尝试添加另一个类型为“类库”的项目吗?然后让这些项目引用它。 - Trevor
@jeffery:请先理解问题。问题是如何添加项目引用,管理员权限与此无关。 - A Coder
EnvDTE版本7是相当古老的一个版本(我相信是Visual Studio 2005)。你有那个DLL吗?否则,你可能需要一个绑定重定向,就像这里的示例:http://msdn.microsoft.com/en-us/library/ms228768.aspx - Simon Mourier
显示剩余5条评论
1个回答

3

NWard是绝对正确的。我不确定你正在尝试使用的代码添加引用,但在项目根目录中的csproj文件可以通过编程方式进行编辑,以将以下内容放在其正确的位置:

<ItemGroup>
    <ProjectReference Include="..\MyOtherProj\MyOtherProj.csproj">
      <Project>{abda85bb-2019-4b80-982e-b90add3fcca0}</Project>
      <Name>MyOtherProj</Name>
    </ProjectReference>
  </ItemGroup>

调用内部的PowerShell脚本或一些控制台exe文件。希望这能帮助你!


我已经通过使用XML处理.csproj文件来完成了这个任务。但是我需要知道是否可以在不使用.csproj文件的情况下添加它。 - A Coder
1
然而问题中并没有提到这一点,实际上,Visual Studio将项目引用存储在csproj文件中(据我所知)。 看看这个链接是否可以帮助您了解相关的见解: http://whathecode.wordpress.com/2012/10/07/conditional-project-or-library-reference-in-visual-studio/ - Vaibhav

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接