11

In a dotnet core 2.0 console application, the output of:

Console.WriteLine("Hello World from "+ System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription);

Is a rather unexpected value:

Hello World from .NET Core 4.6.00001.0

Is there any way to detect .net core 2.0 or later, versus a pre-2.0 .net core platform programmatically? I realize that you probably shouldn't do this in most cases. But in the odd cases where you do need to do this, how would you do this?

DavidG
  • 95,392
  • 10
  • 185
  • 181
Warren P
  • 58,696
  • 38
  • 168
  • 301

3 Answers3

8

You can use preprocessor symbols that are predefined for you. For example:

var isNetCore2 = false;

#if NETCOREAPP2_0
    isNetCore2 = true;
#endif

Console.WriteLine($"Is this .Net Core 2: {isNetCore2}"); 
DavidG
  • 95,392
  • 10
  • 185
  • 181
  • I could have a Netstandard assembly that gets loaded into both .net core 1.0 and 2.0 right? In which case the above would be sub-optimal. – Warren P Aug 18 '17 at 01:24
4

You can try the code below to get the current .NET version.

Tested on .NET Core 1.1 & 2.0

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;
}

https://github.com/dotnet/BenchmarkDotNet/issues/448

Hung Quach
  • 1,786
  • 2
  • 13
  • 25
3

I didn't find any elegant way of doing this, but if you really need to know which version you're running, you can execute dotnet --version like this:

var psi = new ProcessStartInfo("dotnet", "--version")
{
    RedirectStandardOutput = true
};

var process = Process.Start(psi);
process.WaitForExit();

Console.Write(process.StandardOutput.ReadToEnd()); // writes 2.0.0
Michał Dudak
  • 4,609
  • 2
  • 18
  • 25
  • 1
    This may not give you the same version that you are expecting. You system may hold multiple versions of the runtime. – DavidG Sep 12 '17 at 00:25