如何在 .NET Core 中设置全局环境变量(用户范围或系统范围) [英] How to set a global environment variable in .NET Core (user-wide or system-wide)

查看:39
本文介绍了如何在 .NET Core 中设置全局环境变量(用户范围或系统范围)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在完整的 .NET 中,我们可以将 EnvironmentVariableTarget 枚举传递给 Environment.SetEnvironmentVariable 调用:

public enum EnvironmentVariableTarget{过程,用户,机器}

使用 UserMachine 选项,我们可以设置用户范围或系统范围的变量,该变量在应用程序结束后仍然有效:

Environment.SetEnvironmentVariable("foo", "bar", EnvironmentVariableTarget.User);

...

>回声%foo%酒吧

但是,Environment.SetEnvironmentVariable 不接受 .NET Core 中的变量目标.甚至此方法的 XML 注释说:

<块引用>

创建、修改或删除存储在当前进程中的环境变量.

如何在面向 .NET Core 的应用程序中设置用户范围或机器范围的环境变量?只有跨平台解决方案才有意义(至少是 Windows 和 Linux).

解决方案

对于 .NET Core 1.x,它只允许在用户上下文中设置环境变量.通过新的 .NET Core 2.0 预览版,它允许使用 EnvironmentVariableTarget.但是,根据 this GitHub 问题设置用户或机器环境变量不起作用非windows平台.

<块引用>

在非 Windows 平台上使用其他范围(例如用户、机器)未在实现中映射.

GitHub issue 中还描述了使用变通方法检查是否是非 windows 平台设置环境变量.例如:

<前>//省略检查 bash 二进制文件的存在if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) System.Diagnostics.Process.Start("/bin/bash", "-c export " + variable + "=" + value);

In full .NET we can pass EnvironmentVariableTarget enum to Environment.SetEnvironmentVariable call:

public enum EnvironmentVariableTarget
{
    Process,
    User,
    Machine
}

With User or Machine options we can set a user-wide or system-wide variable which stays live after application end:

Environment.SetEnvironmentVariable("foo", "bar", EnvironmentVariableTarget.User);

...

> echo %foo%
bar

However, Environment.SetEnvironmentVariable doesn't accept the variable target in .NET Core. Even XML comment for this method says:

Creates, modifies, or deletes an environment variable stored in the current process.

How to set an user-wide or machine-wide environment variable in .NET Core-targeted app? Only a crossplatform solution makes sense (at least Windows and Linux).

解决方案

For .NET Core 1.x it only allows setting an environment variable in the User context. With the new .NET Core 2.0 preview it allows using the EnvironmentVariableTarget. However, according to this GitHub issue setting User or Machine environment variables doesn't work on non-windows platforms.

Using other scopes (e.g. User, Machine) on non-Windows platforms) is not mapped in the implementation.

Also described in the GitHub issue is to use a workaround to check if it is a non-windows platform to set an environment variable. For example:

// omitting check for presence of bash binary
if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) System.Diagnostics.Process.Start("/bin/bash", "-c export " + variable + "=" + value);

这篇关于如何在 .NET Core 中设置全局环境变量(用户范围或系统范围)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆