'How to get info about the current runtime in C#?

In a C# program, I need to get information about the runtime environment in which the program is running.

Essentially, I need to know if the current program is running in .NET Core or in Full .NET Framework 4.x.

Something like the following might work:

public string GetRuntimeVersion()
{
 #if NET451
    return "net451";
 #elseif netcoreapp11
    return "netcoreapp11"; 
 #elseif netstandard14
    return "netcoreapp14";
 #endif
...
}

But is there a better way?



Solution 1:[1]

Apperently there's also System.Runtime.InteropServices.RuntimeInformation now.

PROPERTIES FrameworkDescription
Gets the name of the .NET installation on which an app is running.

OSArchitecture
Gets the platform architecture on which the current app is running.

OSDescription Gets a string that describes the operating system on which the app is running.

ProcessArchitecture
Gets the process architecture of the currently running app.

RuntimeIdentifier Gets the platform on which an app is running.

https://docs.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.runtimeinformation?view=net-6.0

using System;
                    
public class Program
{
    public static void Main()
    {
        Console.WriteLine(System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription);
        Console.WriteLine(System.Runtime.InteropServices.RuntimeInformation.OSArchitecture);
        Console.WriteLine(System.Runtime.InteropServices.RuntimeInformation.OSDescription);
        Console.WriteLine(System.Runtime.InteropServices.RuntimeInformation.ProcessArchitecture);
        Console.WriteLine(System.Runtime.InteropServices.RuntimeInformation.RuntimeIdentifier);
    }
}
.NET 6.0.0-rtm.21522.10
X64
Linux 5.4.0-1064-azure #67~18.04.1-Ubuntu SMP Wed Nov 10 11:38:21 UTC 2021
X64
debian.11-x64

https://dotnetfiddle.net/sZ3OKj

Funnily enough this doesn't seem to work in powershell, at least not for me when trying to run: [System.Runtime.InteropServices.RuntimeInformation]::RuntimeIdentifier

Solution 2:[2]

Check the System.Environment.Version property (http://msdn.microsoft.com/en-us/library/system.environment.version.aspx).

public static void Main()
{
    Console.WriteLine("Version: {0}", Environment.Version.ToString());
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 sommmen
Solution 2 Jurjen