How to set a global environment variable in .NET Core (user-wide or system-wide)

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

Leave a Comment