如何解决获取代码C#中dotnet项目引用的软件包列表
我想创建我的自定义dotnet工具,并在其实现中,需要获取项目引用的软件包的列表(以及它们依赖的软件包)。 从命令行,我可以运行以下命令来获取该列表:
dotnet list package --include-transitive
我试图找到如何在dotnet sdk存储库中实现此功能,但是存储库如此庞大,很难找到任何东西。
有人知道这个实现的地方吗?或者,更好的是,您可以提供一个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);
}
}
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。