• Uncategorized

About c# : How-to-set-a-global-environment-variable-in-NET-Core-user-wide-or-system-wide

Question Detail

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

public enum EnvironmentVariableTarget

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%

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

Question Answer

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

You may also like...

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.