我的.NET Core 3.0应用程序是使用命令dotnet publish -r win10-x64
或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", ...
,但是也许有更好的方法?
由于找不到其他方法,因此我正在使用.deps.json
文件中找到的值。这是我的代码:
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;
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句