This post will discuss how to get and set environment variables in C#.

You can use the Environment.GetEnvironmentVariable() method to retrieve the value of an environment variable from the process environment block. It returns the environment variable value, or null if the environment variable is not present. For example, the following code retrieves the value of the OS environment variable using the GetEnvironmentVariable() method.

Download  Run Code

 
The following example attempts to fetch an environment variable from the current process. If the variable doesn’t exist, the program creates it using Environment.SetEnvironmentVariable() method and retrieves its value. The environment variable added by the SetEnvironmentVariable() method persists only until the .NET application terminates.

Download  Run Code

 
Note that both GetEnvironmentVariable() and SetEnvironmentVariable() method are overloaded to accept an optional parameter of type EnvironmentVariableTarget enum, which can be either Machine, Process, or User. If it is not provided, the default target is the current process.

That’s all about getting and setting environment variables in C#.