28

I have an aspnetcore webapp and I'd like it to write it's current version, as well as the dotnet core runtime version that it's running on to it's log when it starts up.

I'd like to do this as my webapp runs on various VM's in the cloud and I'd like to be able to look at the logs from all of them and make sure they're all running the same dotnet core runtime version.

What I want is something like this.

App version 1.0.1 running on dotnet 2.0.6

Getting my app version is easy (just assembly version), However, I can't find a way to get the dotnet runtime version?

I've seen various things referencing the Microsoft.DotNet.PlatformAbstractions nuget package, however this doesn't appear to give me the dotnet runtime version at all.

There's also System.Environment.Version, but that reports 4.0.30319.42000 which is the "desktop" dotnet 4.6+ framework version, not the dotnet core version.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Orion Edwards
  • 121,657
  • 64
  • 239
  • 328
  • I'd personally just run "dotnet --version" (via Process.Start) than relying on filesystem path where some assembly is located, like accepted answer. – Evk Mar 16 '18 at 05:15
  • Plus "dotnet --version" can report something like "2.2.0-preview1-008000", which code below cannot. – Evk Mar 16 '18 at 06:24

2 Answers2

62

Since .NET Core 3.0, you can directly call improved API to get such information.

var netCoreVer = System.Environment.Version; // 3.0.0
var runtimeVer = System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription; // .NET Core 3.0.0-preview4.19113.15

Check out this issue

Jerry Bian
  • 3,998
  • 6
  • 29
  • 54
13

For a detailed description you can find the original article here: https://learn.microsoft.com/en-us/dotnet/framework/migration-guide/how-to-determine-which-versions-are-installed

Along with the original github comment chain here: 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;
}
Lucas Trzesniewski
  • 50,214
  • 11
  • 107
  • 158
musicinmyhead
  • 1,466
  • 9
  • 11
  • 4
    So you essentially work out what version it is by looking at it's filesystem location and relying on the convention that microsoft put it in a 2.0.6 folder? Horrible, but I guess effective – Orion Edwards Mar 15 '18 at 21:34