检测 .net core 2.0

11
在一个dotnet core 2.0控制台应用程序中,以下代码的输出结果是:
Console.WriteLine("Hello World from "+ System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription);

是一个相当出人意料的值:

Hello World from .NET Core 4.6.00001.0

有没有办法以编程方式检测 .NET Core 2.0 或更高版本与早期的 .NET Core 平台?我知道在大多数情况下可能不应该这样做。 但在少数需要这样做的情况下,你会如何做到这一点?

3个回答

8

您可以使用预定义的预处理器符号。例如:

var isNetCore2 = false;

#if NETCOREAPP2_0
    isNetCore2 = true;
#endif

Console.WriteLine($"Is this .Net Core 2: {isNetCore2}"); 

我可以有一个 Netstandard 程序集,它可以加载到 .net core 1.0 和 2.0 中,对吧?如果是这样的话,上述情况就不太理想了。 - Warren P

4
您可以尝试下面的代码来获取当前的.NET版本。
在.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


在失败的情况下,返回“未知”可能更友好,而不是返回null。 - Warren P

3

我没有找到任何优雅的方法来实现这一点,但如果你真的需要知道正在运行哪个版本,你可以像这样执行dotnet --version

var psi = new ProcessStartInfo("dotnet", "--version")
{
    RedirectStandardOutput = true
};

var process = Process.Start(psi);
process.WaitForExit();

Console.Write(process.StandardOutput.ReadToEnd()); // writes 2.0.0

1
这可能不会给您您所期望的相同版本。您的系统可能保存有多个运行时版本。 - DavidG

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接