3

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?

Chedy2149
  • 2,821
  • 4
  • 33
  • 56
  • 1
    #if is a compiler directive - you would only ever be able to compile with one of those options - so not be getting the runtime info. – PaulF Apr 06 '17 at 10:32

3 Answers3

5

Microsoft.Extensions.PlatformAbstractions !

using Microsoft.Extensions.PlatformAbstractions;

var runtimeInfo = PlatformServices.Default.Application.RuntimeFramework;

The PlatformServices.Default.Application.RuntimeFramework property contains info such as the identifier of the runtime and its version. And is available on .net core.

Credit goes to:

Community
  • 1
  • 1
Chedy2149
  • 2,821
  • 4
  • 33
  • 56
2

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://learn.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

sommmen
  • 6,570
  • 2
  • 30
  • 51
0

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());
}
Jurjen
  • 1,376
  • 12
  • 19