Skip to main content

Retrieves the value of an environment variable from the current process or from the Windows operating system registry key for the current user or local machine. Optionally throw an Exception if the variable cannot be found.

/// <summary>
/// Retrieves the value of an environment variable from the current
/// process or from the Windows operating system registry key for the
/// current user or local machine.
/// </summary>
/// <param name="variable">The name of an environment variable.</param>
/// <param name="required">Whether or not to throw an exception if the variable is not found. Default is false.</param>
/// <returns>The value of the environment variable, or null if not found.</returns>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="variable"/> is null.</exception>
/// <exception cref="Exception">Thrown if <paramref name="required"/> is true, and the environment variable cannot be found.</exception>
public static string GetEnvVariable(string variable, bool required = false)
{
    if (variable == null)
    {
        throw new ArgumentNullException(nameof(variable), "Environment variable cannot be null");
    }

    var value = Environment.GetEnvironmentVariable(variable, EnvironmentVariableTarget.Process);

    if (value == null)
    {
        value = Environment.GetEnvironmentVariable(variable, EnvironmentVariableTarget.User);
    }

    if (value == null)
    {
        value = Environment.GetEnvironmentVariable(variable, EnvironmentVariableTarget.Machine);
    }

    if (value == null && required)
    {
        throw new Exception("Environment variable could not be retrieved.");
    }

    return value;
}