Get and Set environment variables in C#
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.
|
1 2 3 4 5 6 7 8 9 10 11 |
using System; public class Example { public static void Main() { string? value = Environment.GetEnvironmentVariable("OS"); Console.WriteLine(value); // Windows_NT } } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
using System; public class Example { public static void Main() { string value = Environment.GetEnvironmentVariable("TestEnvironment"); if (value == null) { Environment.SetEnvironmentVariable("TestEnvironment", "Windows"); } value = Environment.GetEnvironmentVariable("TestEnvironment"); Console.WriteLine(value); // Windows } } |
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#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)