Reputation: 68882
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?
Upvotes: 11
Views: 674
Reputation: 2177
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
Upvotes: 3
Reputation: 5048
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
Upvotes: 3
Reputation: 118937
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}");
Upvotes: 8