3

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

Ilya Chumakov
  • 23,161
  • 9
  • 86
  • 114
  • Most linux distributions have different mechanisms of setting environment variables. mac also has it's own (though similar to many linux flavours). You'll need to look at what your target system needs, there is no true cross-platform solution here - i guess only the windows one is the real pain here (on linux it's mostly adding a file in a known location). – Martin Ullrich May 29 '17 at 15:52

1 Answers1

3

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);
Martijn van Put
  • 3,293
  • 18
  • 17