[英]How to set a global environment variable in .NET Core (user-wide or system-wide)
In full .NET we can pass EnvironmentVariableTarget
enum to Environment.SetEnvironmentVariable
call:在完整的 .NET 中,我们可以将
EnvironmentVariableTarget
枚举传递给Environment.SetEnvironmentVariable
调用:
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:使用
User
或Machine
选项,我们可以设置一个用户范围或系统范围的变量,该变量在应用程序结束后仍然有效:
Environment.SetEnvironmentVariable("foo", "bar", EnvironmentVariableTarget.User);
... ...
> echo %foo%
bar
However, Environment.SetEnvironmentVariable
doesn't accept the variable target in .NET Core.但是,
Environment.SetEnvironmentVariable
不接受 .NET Core 中的变量目标。 Even XML comment for this method says:甚至此方法的 XML 注释也说:
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?如何在面向 .NET Core 的应用程序中设置用户范围或机器范围的环境变量? Only a crossplatform solution makes sense (at least Windows and Linux).
只有跨平台解决方案才有意义(至少是 Windows 和 Linux)。
For .NET Core 1.x it only allows setting an environment variable in the User context.对于 .NET Core 1.x,它只允许在用户上下文中设置环境变量。 With the new .NET Core 2.0 preview it allows using the
EnvironmentVariableTarget
.使用新的 .NET Core 2.0 预览版,它允许使用
EnvironmentVariableTarget
。 However, according to this GitHub issue setting User or Machine environment variables doesn't work on non-windows platforms.但是,根据此GitHub 问题,设置用户或机器环境变量在非 Windows 平台上不起作用。
Using other scopes (eg User, Machine) on non-Windows platforms) is not mapped in the implementation.
在非 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. GitHub issue中还描述了使用一种解决方法来检查是否是非windows平台设置环境变量。 For example:
例如:
// omitting check for presence of bash binary if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) System.Diagnostics.Process.Start("/bin/bash", "-c export " + variable + "=" + value);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.