简体   繁体   English

在 .NET Core 应用程序中确定运行时目标 (OS)

[英]Determine runtime target (OS) in .NET Core app

My .NET Core 3.0 app is published for different operating systems, using the commands dotnet publish -r win10-x64 or dotnet publish -r ubuntu.18.04-x64 for example.我的 .NET Core 3.0 应用程序针对不同的操作系统发布,例如使用命令dotnet publish -r win10-x64dotnet publish -r ubuntu.18.04-x64

During runtime, in my C# code I want to find out the target the app was built for.在运行时,在我的 C# 代码中,我想找出构建应用程序的目标。 I do not mean just the general operating system like Windows or Linux (as asked here ), but the exact runtime target, like ubuntu-18.04-x64 .我不仅仅指像 Windows 或 Linux 之类的通用操作系统( 如此处所问),而是指确切的运行时目标,例如ubuntu-18.04-x64

I already found out, that there is a file <AssemblyName>.deps.json .我已经发现,有一个文件<AssemblyName>.deps.json It contains the property "runtimeTarget": { "name": ".NETCoreApp,Version=v3.0/ubuntu.18.04-x64", ... , but maybe there is a better way?它包含属性"runtimeTarget": { "name": ".NETCoreApp,Version=v3.0/ubuntu.18.04-x64", ... ,但也许有更好的方法?

I am using the code given below with.Net core version 2 (and 1.2 in the past) -我将下面给出的代码与.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.");
        }
    }

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

On my windows machine the output looks as below - Image displaying version output of code above在我的 windows 机器上,output 如下所示 -图像显示版本 output 的代码

Since I found no other way, I am using the value found in the .deps.json file.由于我没有找到其他方法,因此我使用.deps.json文件中的值。 Here is my code:这是我的代码:

using Newtonsoft.Json.Linq;
using System;
using System.IO;

/// <summary>
/// Returns the current RID (Runtime IDentifier) where this applications runs.
/// See https://docs.microsoft.com/en-us/dotnet/core/rid-catalog for possible values, e.g. "ubuntu.18.04-x64".
/// The value is read from the first found .deps.json file in the application folder, at the path
/// "runtimeTarget"/"name" the value behind the last "/".
/// When the file or the value behind the last "/" is missing, this application folder was not compiled
/// for a specific runtime, and null is returned.
/// </summary>
public static string? GetRuntimeIdentifier() {
    try {
        // Find first (and probably only) .deps.json file in the application's folder.
        var dir = AppDomain.CurrentDomain.BaseDirectory;
        var files = Directory.GetFiles(dir, "*.deps.json");
        if (files.Length == 0)
            return null;
        // Read JSON content
        var json = JObject.Parse(File.ReadAllText(Path.Combine(dir, files[0])));
        var name = json["runtimeTarget"]["name"].ToString();
        // Read RID after slash
        var slashPos = name.LastIndexOf('/');
        if (slashPos == -1)
            return null;
        return name.Substring(slashPos + 1);
    }
    catch {
        // Unexpected file format or other problem
        return null;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 对于需要使用“ .NET Core版本2+”创建的软件,需要“上线”运行,是否有任何理由在目标“下线” OS上安装.NET Core Runtime? - For software created with .NET Core Version 2+, that needs to go “live”, is there any reason to install the .NET Core Runtime on the target “live” OS? 如何确定.net应用程序是否是“核心”应用程序? - how to determine if a .net app is a “core” app? 在 ASP.NET Core 6 中确定运行时的健康检查路由 - Determine health check routes at runtime in ASP.NET Core 6 .NET Core 有条件的发布取决于发布的目标运行时 - .NET Core Conditional publishing depending on Published Target Runtime 无法发布.NET Core应用程序(不受支持的运行时) - Unable to publish .NET Core app (unsupported runtime) Azure 应用服务 - 更新 .NET Core 运行时 - Azure App Service - update .NET Core runtime Linux上的.net核心应用程序目标.net框架4.5.2 - .net core app target .net framework 4.5.2 on Linux 如何确定asp.net核心应用程序将在哪个环境中运行? - How to determine which environment asp.net core app will run in? 如何在Mac OS上执行.net核心控制台应用程序 - how do I execute a .net core console app on mac os 如何检测我的Asp.Net Core应用程序运行的操作系统? - How to detect OS my Asp.Net Core app is running on?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM