System.Environment.SetEnvironmentVariable Method

Creates, modifies, or deletes an environment variable stored in the current process or in the Windows operating system registry key reserved for the current user or local machine.

Syntax

public static void SetEnvironmentVariable (string variable, string value, EnvironmentVariableTarget target)

Parameters

variable
The name of an environment variable.
value
A value to assign to variable.
target
One of the EnvironmentVariableTarget values.

Remarks

If the value parameter is not empty and the environment variable named by the variable parameter does not exist, the environment variable is created and assigned the contents of value. Solely for the purposes of this operation, value is considered empty if it is null, contains a zero-length string, or contains an initial hexadecimal zero character (0x00).

If variable contains a non-initial hexadecimal zero character, the characters before the zero character are considered the environment variable name and all subsequent characters are ignored.

If value contains a non-initial hexadecimal zero character, the characters before the zero character are assigned to the environment variable and all subsequent characters are ignored.

If value is empty and the environment variable named by variable exists, the environment variable is deleted. If variable does not exist, no error occurs even though the operation cannot be performed. Exercise caution when target is EnvironmentVariableTarget.Machine because you can delete an environment variable that affects your entire local machine, not just the current process or user.

If target is EnvironmentVariableTarget.User, the environment variable is stored in the Windows registry key reserved for the current user. It is also copied to instances of File Explorer that are running as the current user. The environment variable is then inherited by any new processes that the user launches from File Explorer.

Similarly, if target is EnvironmentVariableTarget.Machine, the environment variable is stored in the Windows registry key reserved for the local computer. It is also copied to all instances of File Explorer. The environment variable is then inherited by any new processes that are launched from File Explorer.

If target is EnvironmentVariableTarget.User or EnvironmentVariableTarget.Machine, other applications are notified of the set operation by a Windows WM_SETTINGCHANGE message.

If target is EnvironmentVariableTarget.User or EnvironmentVariableTarget.Machine, it is recommended that the length of value be less than 2048 characters.

Requirements

Namespace: System
Assembly: mscorlib (in mscorlib.dll)
Assembly Versions: 2.0.0.0, 4.0.0.0
Since: .NET 2.0