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

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

问题描述

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

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

public enum EnvironmentVariableTarget
{
    Process,
    User,
    Machine
}

使用 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

但是, Environment.SetEnvironmentVariable 在.NET Core中不接受变量目标。甚至对此方法的XML注释都表明:

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


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

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

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).

推荐答案

对于.NET Core 1.x,它仅允许设置用户上下文中的环境变量。借助新的.NET Core 2.0预览版,它允许使用 EnvironmentVariableTarget 。但是,根据 GitHub问题设置,用户或计算机环境变量不起作用非Windows平台。

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.


在实现中未映射使用其他作用域(例如,非Windows平台上的用户,计算机)。

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

在GitHub问题中也描述了使用变通方法来检查它是否是非Windows平台来设置环境变量。例如:

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天全站免登陆