You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET Core 6如何在运行时检测NuGet包引用及版本?

解决.NET Core 6中运行时检测NuGet包引用及版本的问题

你的项目.csproj配置如下:

<ItemGroup>
  <PackageReference Include="Foo" Version="1.2.3" />
  <PackageReference Include="Bar" Version="4.5.6" />
</ItemGroup>

你尝试Assembly.GetExecutingAssembly().GetReferencedAssemblies()、Assembly.GetEntryAssembly().GetReferencedAssemblies()、AppDomain.CurrentDomain.GetAssemblies()这些方法均未成功,核心问题是NuGet.CommandLine包未加载到AppDomain中,以下是几种可行的解决办法:

方法一:显式加载程序集并读取信息

如果目标包的程序集未被自动加载,可以尝试显式加载后获取版本。注意程序集名称通常和NuGet包名一致(比如NuGet.CommandLine对应的程序集为NuGet.CommandLine.dll):

try
{
    var assembly = Assembly.Load("NuGet.CommandLine");
    var version = assembly.GetName().Version;
    Console.WriteLine($"已引用NuGet.CommandLine,版本:{version}");
}
catch (FileNotFoundException)
{
    Console.WriteLine("未引用NuGet.CommandLine");
}

方法二:直接解析项目配置文件

如果不需要加载程序集,仅需确认是否存在引用,可以直接读取.csproj或生成的packages.lock.json文件,解析配置获取包信息:

解析.csproj示例

var projectPath = Path.Combine(AppContext.BaseDirectory, "你的项目文件名.csproj");
var doc = XDocument.Load(projectPath);
var ns = XNamespace.Get("http://schemas.microsoft.com/developer/msbuild/2003");
var packageReferences = doc.Descendants(ns + "PackageReference");

foreach (var refElem in packageReferences)
{
    var name = refElem.Attribute("Include")?.Value;
    var version = refElem.Attribute("Version")?.Value;
    if (name == "NuGet.CommandLine")
    {
        Console.WriteLine($"已引用NuGet.CommandLine,版本:{version}");
    }
}

方法三:使用DependencyContext获取依赖信息

.NET Core/.NET 5+提供的DependencyContext类可直接获取应用所有依赖包信息,不受程序集是否加载的影响:
首先添加对应NuGet包引用:

<PackageReference Include="Microsoft.Extensions.DependencyModel" Version="6.0.0" />

然后编写检测代码:

var context = DependencyContext.Default;
var targetPackage = context.RuntimeLibraries.FirstOrDefault(l => 
    l.Name.Equals("NuGet.CommandLine", StringComparison.OrdinalIgnoreCase));

if (targetPackage != null)
{
    Console.WriteLine($"已引用NuGet.CommandLine,版本:{targetPackage.Version}");
}
else
{
    Console.WriteLine("未引用NuGet.CommandLine");
}

内容的提问来源于stack exchange,提问作者lonix

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 11:03:15