以编程方式获取dotnet核心运行时的当前运行版本

Ori*_*rds 2 c# .net-core

我有一个aspnetcore Web应用程序,我希望它编写它的当前版本,以及它启动时在其日志上运行的dotnet core运行时版本。

我想这样做,因为我的Web应用程序可以在云中的各种VM上运行,并且希望能够查看所有日志中的日志,并确保它们都运行相同的dotnet核心运行时版本。

我想要的是这样的东西。

App version 1.0.1 running on dotnet 2.0.6
Run Code Online (Sandbox Code Playgroud)

获取我的应用程序版本很容易(只是汇编版本),但是,我找不到获取dotnet运行时版本的方法吗?

我已经看到了各种各样的东西,都引用了Microsoft.DotNet.PlatformAbstractions nuget包,但是这似乎根本没有给我dotnet运行时版本。

还有System.Environment.Version,但是它报告的4.0.30319.42000“桌面” dotnet 4.6+框架版本,而不是dotnet核心版本。

有人可以帮忙吗?

谢谢

Jer*_*ian 38

从 .NET Core 3.0 开始,您可以直接调用改进的 API 来获取此类信息。

var netCoreVer = System.Environment.Version; // 3.0.0
var runtimeVer = System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription; // .NET Core 3.0.0-preview4.19113.15
Run Code Online (Sandbox Code Playgroud)

看看这个问题


mus*_*ead 5

有关详细说明,您可以在这里找到原始文章:https : //docs.microsoft.com/zh-cn/dotnet/framework/migration-guide/how-to-determine-which-versions-are-installed

连同原始的github评论链在这里:https : //github.com/dotnet/BenchmarkDotNet/issues/448

public static string GetNetCoreVersion() {
  var assembly = typeof(System.Runtime.GCSettings).GetTypeInfo().Assembly;
  var assemblyPath = assembly.CodeBase.Split(new[] { '/', '\\' }, StringSplitOptions.RemoveEmptyEntries);
  int netCoreAppIndex = Array.IndexOf(assemblyPath, "Microsoft.NETCore.App");
  if (netCoreAppIndex > 0 && netCoreAppIndex < assemblyPath.Length - 2)
    return assemblyPath[netCoreAppIndex + 1];
  return null;
}
Run Code Online (Sandbox Code Playgroud)

  • 因此,通过查看文件系统的位置并依靠Microsoft将其放在2.0.6文件夹中的约定,您实际上可以确定它是什么版本?糟透了,但我想有效 (3认同)