【问题标题】:Detecting .net core 2.0检测 .net core 2.0
【发布时间】:2019-05-19 07:19:23
【问题描述】:

在 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 或更高版本,而不是 2.0 之前的 .net core 平台?我意识到在大多数情况下您可能不应该这样做。但在您确实需要这样做的奇怪情况下,您将如何做到这一点?

【问题讨论】:

    标签: c# .net-core .net-core-2.0


    【解决方案1】:

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

    var isNetCore2 = false;
    
    #if NETCOREAPP2_0
        isNetCore2 = true;
    #endif
    
    Console.WriteLine($"Is this .Net Core 2: {isNetCore2}"); 
    

    【讨论】:

    • 我可以将 Netstandard 程序集加载到 .net core 1.0 和 2.0 中,对吗?在这种情况下,上述情况将是次优的。
    【解决方案2】:

    您可以尝试下面的代码来获取当前的 .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 可能更友好。
    【解决方案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
    

    【讨论】:

    • 这可能不会为您提供您期望的相同版本。您的系统可能拥有多个版本的运行时。
    猜你喜欢
    • 2018-02-20
    • 1970-01-01
    • 2018-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-03
    • 2018-04-01
    相关资源
    最近更新 更多