如何在C#中获取有关当前运行时的信息?

Che*_*149 2 c# .net-4.0 .net-core

在C#程序中,我需要获取有关运行程序的运行时环境的信息.

基本上,我需要知道当前程序是在.NET Core还是在.NET Framework 4.x中运行.

像下面这样的东西可能会起作用:

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

但有更好的方法吗?

Che*_*149 5

Microsoft.Extensions.PlatformAbstractions!

using Microsoft.Extensions.PlatformAbstractions;

var runtimeInfo = PlatformServices.Default.Application.RuntimeFramework;
Run Code Online (Sandbox Code Playgroud)

该PlatformServices.Default.Application.RuntimeFramework属性包含诸如运行时标识符及其版本之类的信息.并且可以在.net核心上获得.

归功于: