首页 > 解决方案 > 获取代码c#中dotnet项目引用的包列表

问题描述

我想创建我的自定义 dotnet 工具,在其实现中,我需要获取项目引用的包列表(以及它们所依赖的包)。从命令行,我可以运行这样的东西来获取该列表:

dotnet list package --include-transitive

我试图在 dotnet sdk repo 中找到它是如何实现的,但是 repo 太大了,很难找到任何东西。

有谁知道这是在哪里实现的,或者更好的是,您能否提供一个 C# 代码示例,说明如何在代码中获取此列表。

标签: c#.netcommand-line-interface

解决方案


我遵循了@alexandru-clonțea 的建议,并在github上试用了代码。在我看来,它实际上正确地回答了这个问题。它涉及在项目上运行 dotnet restore 并生成依赖关系图文件,然后使用 NuGet.ProjectModel 库读取该文件。读取依赖的代码的核心部分是这样的:

using System;
using System.IO;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NuGet.ProjectModel;

namespace YourNamespace
{
    /// <remarks>
    /// Credit for the stuff happening in here goes to the https://github.com/jaredcnance/dotnet-status project
    /// </remarks>
    public class DependencyGraphService
    {
        public DependencyGraphSpec GenerateDependencyGraph(string projectPath)
        {
            var tempFile = Path.Combine(Path.GetTempPath(), Path.GetTempFileName());
            var arguments = new[] {"msbuild", $"\"{projectPath}\"", "/t:GenerateRestoreGraphFile", $"/p:RestoreGraphOutputPath={tempFile}"};

            try
            {
                var runStatus = DotNetRunner.Run(Path.GetDirectoryName(projectPath), arguments);

                if (!runStatus.IsSuccess)
                    throw new Exception($"Unable to process the the project `{projectPath}. Are you sure this is a valid .NET Core or .NET Standard project type?" +
                                        $"\r\n\r\nHere is the full error message returned from the Microsoft Build Engine:\r\n\r\n" + runStatus.Output);

                return new DependencyGraphSpec(JsonConvert.DeserializeObject<JObject>(File.ReadAllText(tempFile)));
            }
            finally
            {
                if(File.Exists(tempFile))
                    File.Delete(tempFile);
            }
        }
    }
}


推荐阅读