c# - 获取代码c#中dotnet项目引用的包列表
问题描述
我想创建我的自定义 dotnet 工具,在其实现中,我需要获取项目引用的包列表(以及它们所依赖的包)。从命令行,我可以运行这样的东西来获取该列表:
dotnet list package --include-transitive
我试图在 dotnet sdk repo 中找到它是如何实现的,但是 repo 太大了,很难找到任何东西。
有谁知道这是在哪里实现的,或者更好的是,您能否提供一个 C# 代码示例,说明如何在代码中获取此列表。
解决方案
我遵循了@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);
}
}
}
}
推荐阅读
- php - XTC 网站具有新的第二个域
- javascript - 发送者断开连接后保持 Chromecast CAF 接收器活动
- c# - 将定义的名称放在asp.net c#的reportviewer PDF中
- r - 创建假人时遇到问题
- c# - 不能多次初始化 var 变量
- google-bigquery - 将 Dataflow 模板 GCS 调试到 BigQuery
- python - 如何使用正则表达式根据列条目选择行进行过滤?
- outlook-addin - 用 vb 收听特定的 Outlook 帐户
- angular - 无法安装新版本的 angular/cli
- mysql - 脚本化 Jenkinsfile 中的多个 Docker