Environment Variables in C#

Environment variables are a universal mechanism for conveying configuration information to programs. Let’s look at how to set, get, and list environment variables in C#.

using System;
using System.Collections;

class EnvironmentVariables
{
    static void Main()
    {
        // To set a key/value pair, use Environment.SetEnvironmentVariable.
        // To get a value for a key, use Environment.GetEnvironmentVariable.
        // This will return null if the key isn't present in the environment.
        Environment.SetEnvironmentVariable("FOO", "1");
        Console.WriteLine("FOO: " + Environment.GetEnvironmentVariable("FOO"));
        Console.WriteLine("BAR: " + Environment.GetEnvironmentVariable("BAR"));

        // Use Environment.GetEnvironmentVariables to list all key/value pairs in the
        // environment. This returns an IDictionary of strings.
        // Here we print all the keys.
        Console.WriteLine();
        foreach (DictionaryEntry de in Environment.GetEnvironmentVariables())
        {
            Console.WriteLine(de.Key);
        }
    }
}

Running the program shows that we pick up the value for FOO that we set in the program, but that BAR is null.

FOO: 1
BAR:

The list of keys in the environment will depend on your particular machine.

PROCESSOR_ARCHITECTURE
PATH
USERPROFILE
...
FOO

If we set BAR in the environment first, the running program picks that value up. In C#, you can set environment variables before running the program using the command prompt:

C:\> set BAR=2
C:\> dotnet run
FOO: 1
BAR: 2
...

Note that the exact method of setting environment variables may vary depending on your operating system and how you’re running the C# program.