首页 > 解决方案 > 确定 .NET Core 应用程序中的运行时目标 (OS)

问题描述

我的 .NET Core 3.0 应用程序是针对不同的操作系统发布的,使用命令dotnet publish -r win10-x64dotnet publish -r ubuntu.18.04-x64例如。

在运行时,在我的 C# 代码中,我想找出构建应用程序的目标。我不仅仅指像 Windows 或 Linux 这样的通用操作系统(如此处所问,而是指确切的运行时目标,如ubuntu-18.04-x64.

我已经发现,有一个文件<AssemblyName>.deps.json。它包含属性"runtimeTarget": { "name": ".NETCoreApp,Version=v3.0/ubuntu.18.04-x64", ...,但也许有更好的方法?

标签: c#.net-core

解决方案


我将下面给出的代码与 .Net 核心版本 2(以及过去的 1.2)一起使用 -

    public static void PrintTargetRuntime()
    {
            var framework = Assembly
                    .GetEntryAssembly()?
                    .GetCustomAttribute<TargetFrameworkAttribute>()?
                    .FrameworkName;

            var stats = new
        {
            OsPlatform = System.Runtime.InteropServices.RuntimeInformation.OSDescription,
            OSArchitecture = System.Runtime.InteropServices.RuntimeInformation.OSArchitecture,
            ProcesArchitecture = System.Runtime.InteropServices.RuntimeInformation.ProcessArchitecture,
            FrameworkDescription = System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription,
            AspDotnetVersion = framework
        };

        Console.WriteLine("Framework version is " + framework);
        Console.WriteLine("OS Platform is : " + stats.OsPlatform );
        Console.WriteLine("OS Architecture is : " + stats.OSArchitecture);
        Console.WriteLine("Framework description is " + stats.FrameworkDescription);
        Console.WriteLine("ASPDotNetVersion is " + stats.AspDotnetVersion);

        if (stats.ProcesArchitecture == Architecture.Arm)
        {
            Console.WriteLine("ARM process.");
        }
        else if (stats.ProcesArchitecture == Architecture.Arm64)
        {
            Console.WriteLine("ARM64 process.");
        }
        else if (stats.ProcesArchitecture == Architecture.X64)
        {
            Console.WriteLine("X64 process.");
        }
        else if (stats.ProcesArchitecture == Architecture.X86)
        {
            Console.WriteLine("x86 process.");
        }
    }

我已经在 Windows 10 和 MacOS Mojave 上对此进行了测试。这来自这里 - https://weblog.west-wind.com/posts/2018/Apr/12/Getting-the-NET-Core-Runtime-Version-in-a-Running-Application

在我的 Windows 机器上,输出如下所示 - 图像显示上面代码的版本输出


推荐阅读