C#获取作为项目的项目引用

时间:2019-05-09 08:45:27

标签: c# runtime system.reflection

是否可以获取我的项目具有的所有项目引用?因此,例如,我的项目A引用了项目B和项目C。我不想获得诸如库之类的所有内容的引用,而我的解决方案中只是其他项目。我需要用代码编写,以便将其保存在数据库中。

5 个答案:

答案 0 :(得分:1)

您可以使用Microsoft.Build.Evaluation中的类来解决这个问题。

具体地说,是ProjectCollection类。要使用此功能,您需要在项目中添加以下引用:

  • Microsoft.Build
  • Microsoft.Build.Utilities.Core

(通过引用管理器添加它们时,请查看“程序集->扩展名”,否则您可能会引用不适用于较新项目文件的旧版本。)

然后,您可以编写如下代码来遍历所有项目引用:

using System;
using Microsoft.Build.Evaluation;

namespace Demo
{
    class Program
    {
        static void Main()
        {
            var projectCollection = new ProjectCollection();
            var projFile          = @"E:\Test\CS7\ConsoleApp1\ConsoleApp1.csproj";
            var project           = projectCollection.LoadProject(projFile);
            var projectReferences = project.GetItems("ProjectReference");

            foreach (var projectReference in projectReferences)
            {
                Console.WriteLine(projectReference.EvaluatedInclude);
            }
        }
    }
}

答案 1 :(得分:0)

您可以右键单击每个项目,然后导航到BuildDependencies> ProjectDependencies。

假定您不打算编写外部项目分析器/依赖关系图创建器。

根据评论更新: 如果您正在执行静态代码分析器(遍历解决方案中的文件),则可以迭代.csproj文件并提取如下部分:

  <ItemGroup>
    <ProjectReference Include="..\xyz.Service.Client\xyz.Service.Client.csproj" />
    <ProjectReference Include="..\xyz.Service.Interface\xyz.Service.Interface.csproj" />
    <ProjectReference Include="..\xyz.Web.Interface\xyz.Web.Interface.csproj" />
  </ItemGroup>

您可以将其映射到所需的dto结构,并按需要保存它。以下是一些可能简化解决方案的代码:

XNamespace msbuild = "http://schemas.microsoft.com/developer/msbuild/2003";
XDocument projDefinition = XDocument.Load(fullProjectPath);
IEnumerable<string> references = projDefinition
    .Element(msbuild + "Project")
    .Elements(msbuild + "ItemGroup")
    .Elements(msbuild + "Reference")
    .Select(refElem => refElem.Value);
foreach (string reference in references)
{
    Console.WriteLine(reference);
}

答案 2 :(得分:0)

不幸的是,没有可以检查的“ IsPartOfSolution”标志。

但是将整个列表压缩下来相对容易:

IEnumerable<Assembly> assemblies = AppDomain.CurrentDomain.GetAssemblies().Where(a => a.FullName.Contains("SolutionName"));  

答案 3 :(得分:0)

听起来像是代码分析器,

如果您启动一个新的“独立代码分析工具”项目,将为您生成一个相当完整的示例项目。 我不太确定它能走多远,但最终会遇到一个SolutionLoader对象。

遍历loader.Solution.Projects,以获取解决方案中的所有项目。 每个Project都有一个ProjectId和一个属性AllProjectReferences(其中包括项目外部的引用)。

通过解决方案中包含的projectId过滤这些内容,可以助您一臂之力。

答案 4 :(得分:0)

我在vb.net中有此代码可以满足您的要求:

Private Sub GetProjectReferences()
    Dim lines = New List(Of String)
    Dim path = "..\..\TestApp.vbproj"
    For Each line In File.ReadAllLines(path)
        If line.Contains("<ProjectReference") Then
            Dim projNameWithExtension = line.Substring(line.LastIndexOf("\") + 1)
            Dim projName = projNameWithExtension.Substring(0, projNameWithExtension.IndexOf(".vbproj"))
            lines.Add(projName)
        End If
    Next
End Sub

如果将其转换为c#(函数和变量定义,并将.vbproj转换为.csproj),则可能会有用