c# - 确定 .NET Core 应用程序中的运行时目标 (OS)
问题描述
我的 .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", ...
,但也许有更好的方法?
解决方案
我将下面给出的代码与 .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 机器上,输出如下所示 - 图像显示上面代码的版本输出
推荐阅读
- json - jq 对域名和 dns 记录的字符串操作
- docker - 在 docker 容器中创建对等通道失败:身份无效:x509:证书由未知机构签名
- c# - 当字节值 > 127 时,C# AES 解密返回 0x3F (0011 1111)
- computer-vision - 输出和损失函数的适当激活函数以优化 OCR?
- python - AttributeError:“NoneType”对象没有属性“保存”python-django
- python - 二叉树搜索未排序的矩阵?
- flutter - Completer Flutter hook 导致错误状态错误
- c# - 如何指定一个位置来为 Entity Framework Core 应用程序创建数据库文件?
- wso2 - 身份服务器 - 添加服务提供者空白页
- reactjs - 如何在 ReactJS 中链接动作?