Ideally you should not care too much about the version of .NET you are running on. There are better
techniques like using reflection to check for features or by using
self-contained deployment
to completely control the version of .NET included with your application.
Library authors targeting .NET Standard however often need to customize behavior depending on which
type of .NET try are running on.
Detecting the version of modern .NET
If you are targeting .NET Core 3.0 or later (and to be clear, this also applies if you are targeting .NET 5 and later),
the answer is very simple:
Environment.Version
returns the version of the .NET runtime and
RuntimeInformation.FrameworkDescription
returns a textual description like .NET Core 3.1.32
or .NET 7.0.12
. See
this breaking change notice
that describes this behavior.
If you are targeting earlier versions of .NET Core or the .NET Framework, the story is more complicated.
Detecting different types of .NET
If you merely want to differentiate between .NET Framework and .NET (nee .NET Core), you can use the
RuntimeInformation.FrameworkDescription
property.
For example, if you are just trying to figure out whether your should dynamically load an assembly for
.NET or .NET Framework, this property should be enough. It exists on every version of .NET Core (and .NET),
so if the property does not exist your are probably running on an older version of .NET Framework.
You can do something like this:
using System.Runtime.InteropServices;
Assembly a;
if (RuntimeInformation.FrameworkDescription.StartsWith(".NET Framework"))
{
a = Assembly.LoadFile("netfx/MyAssembly.dll");
}
else
{
a = Assembly.LoadFile("netcore/MyAssembly.dll");
}
Older frameworks
If you are running on .NET Framework and really need to know version, you will have to use the
registry method.
Note that .NET Framework looks are the target framework of your application and changes its behavior
to preserve backwards compatibility, so there are limits to this approach.
If you are trying to detect the exact version of .NET Core prior to 3.0, there are not any good answers
that I know of. If you are in a
framework-dependant application,
you can look at location of system assembly and parse out a version from. For example, this:
Console.WriteLine(typeof(object).Assembly.Location)
prints this when running on my machine:
C:\Program Files\dotnet\shared\Microsoft.NETCore.App\2.2.8\System.Private.CoreLib.dll
You can see the version in the file path, but I don’t think this is a reliable way to detect the version.
For example, this would not work in a self-contained .NET Core app.