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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With