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

And*_*ndi 7 c# .net-core

dotnet publish -r win10-x64我的 .NET Core 3.0 应用程序是使用命令或dotnet 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", ...,但也许有更好的方法?

And*_*ndi 0

由于我找不到其他方法,因此我使用文件中找到的值.deps.json。这是我的代码:

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

/// <summary>
/// Returns the current RID (Runtime IDentifier) where this applications runs.
/// See https://learn.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;
    }
}
Run Code Online (Sandbox Code Playgroud)