简体   繁体   中英

Detecting .net core 2.0

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?

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM