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

时间:2018-03-15 21:00:15

标签: c# .net-core

我有一个aspnetcore webapp,我希望它能够编写它的当前版本,以及它在启动时运行到它的日志上的dotnet核心运行时版本。

我想这样做,因为我的webapp运行在云中的各种虚拟机上,我希望能够查看所有虚拟机的日志,并确保它们都运行相同的dotnet核心运行时版本

我想要的是这样的。

App version 1.0.1 running on dotnet 2.0.6

获取我的应用版本很简单(只是汇编版本),但是,我找不到获取dotnet运行时版本的方法?

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

还有System.Environment.Version,但报告的4.0.30319.42000"desktop" dotnet 4.6+ framework version,而不是dotnet核心版本。

有人可以帮忙吗?

由于

2 个答案:

答案 0 :(得分:10)

从.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

查看此issue

答案 1 :(得分:5)

有关详细说明,请在此处找到原始文章: https://docs.microsoft.com/en-us/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;
}