Environment variables
suggest changeEnvironment variables are name/value string pairs that the operating system passes to every process. They are the standard way to give a program configuration that changes between machines or deployments: database hosts, API keys, ports, feature flags, log levels. Docker, Kubernetes, CI systems and cloud hosts all inject configuration this way.
In .NET everything lives in the static System.Environment class:
Environment.GetEnvironmentVariable(name)reads one variableEnvironment.GetEnvironmentVariables()returns all of themEnvironment.SetEnvironmentVariable(name, value)sets or deletes oneEnvironment.ExpandEnvironmentVariables(text)replaces%NAME%references in a string
System is part of the implicit usings of modern projects, so no using is needed.
Reading a variable
string? home = Environment.GetEnvironmentVariable("HOME"); // Linux / macOS
string? profile = Environment.GetEnvironmentVariable("USERPROFILE"); // Windows
Console.WriteLine($"HOME: {home ?? "(not set)"}");
Console.WriteLine($"USERPROFILE: {profile ?? "(not set)"}");
Output on Windows:
HOME: (not set)
USERPROFILE: C:\Users\kjk
GetEnvironmentVariable returns null when the variable doesn't exist, so the return type is string?. The ?? operator is the idiomatic way to supply a default:
string env = Environment.GetEnvironmentVariable("APP_ENV") ?? "development";
string logLevel = Environment.GetEnvironmentVariable("LOG_LEVEL") ?? "Information";
Console.WriteLine($"{env} / {logLevel}");
development / Information
A variable can exist with an empty value (export APP_ENV= in bash). ?? won't replace an empty string. If empty should count as missing, check for it:
string? raw = Environment.GetEnvironmentVariable("APP_ENV");
string env = string.IsNullOrWhiteSpace(raw) ? "development" : raw;
Case sensitivity
Variable names are case-insensitive on Windows and case-sensitive on Linux and macOS:
bool found = Environment.GetEnvironmentVariable("path") is not null;
Console.WriteLine(found ? "case-insensitive" : "case-sensitive");
case-insensitive // Windows
case-sensitive // Linux, macOS
Always use the exact spelling (by convention UPPER_SNAKE_CASE) so the code works everywhere.
Parsing typed values
Environment variables are always strings. Convert them yourself and decide what happens when the value is missing or malformed. Use TryParse with CultureInfo.InvariantCulture so the result doesn't depend on the machine's locale:
using System.Globalization;
int port = EnvInt("PORT", 5000);
bool verbose = EnvBool("VERBOSE");
TimeSpan timeout = TimeSpan.Parse(
Environment.GetEnvironmentVariable("TIMEOUT") ?? "00:00:10",
CultureInfo.InvariantCulture);
Console.WriteLine($"port={port} verbose={verbose} timeout={timeout}");
static int EnvInt(string name, int defaultValue) =>
int.TryParse(Environment.GetEnvironmentVariable(name),
NumberStyles.Integer, CultureInfo.InvariantCulture, out int value)
? value
: defaultValue;
static bool EnvBool(string name, bool defaultValue = false) =>
Environment.GetEnvironmentVariable(name)?.Trim().ToLowerInvariant() switch
{
"1" or "true" or "yes" or "on" => true,
"0" or "false" or "no" or "off" => false,
_ => defaultValue,
};
Running with PORT=8080 VERBOSE=true TIMEOUT=00:00:30:
port=8080 verbose=True timeout=00:00:30
bool.TryParse only accepts true / false, while users often write 1 or yes, which is why EnvBool handles a few common spellings.
Required variables
For settings the program cannot run without, such as a connection string or API key, fail fast at startup with a clear message instead of crashing later with a NullReferenceException:
string apiKey = RequireEnv("API_KEY");
static string RequireEnv(string name) =>
Environment.GetEnvironmentVariable(name) is { Length: > 0 } value
? value
: throw new InvalidOperationException(
$"Required environment variable '{name}' is not set");
Unhandled exception. System.InvalidOperationException: Required environment variable 'API_KEY' is not set
Listing all variables
GetEnvironmentVariables() returns a non-generic IDictionary (a Hashtable) whose keys and values are object. Cast the entries to DictionaryEntry to sort them or use LINQ:
using System.Collections;
IDictionary vars = Environment.GetEnvironmentVariables();
foreach (DictionaryEntry e in vars.Cast<DictionaryEntry>()
.OrderBy(e => (string)e.Key)
.Take(5))
{
Console.WriteLine($"{e.Key}={e.Value}");
}
Console.WriteLine($"Total: {vars.Count}");
ALLUSERSPROFILE=C:\ProgramData
APPDATA=C:\Users\kjk\AppData\Roaming
CommonProgramFiles=C:\Program Files\Common Files
COMPUTERNAME=DESKTOP-1
ComSpec=C:\WINDOWS\system32\cmd.exe
Total: 64
To work with a typed dictionary, convert it once:
Dictionary<string, string> env = Environment.GetEnvironmentVariables()
.Cast<DictionaryEntry>()
.ToDictionary(e => (string)e.Key, e => (string)e.Value!);
var appVars = env.Where(kv => kv.Key.StartsWith("MYAPP_"));
Setting and deleting variables
SetEnvironmentVariable changes the environment of the current process only. The change is visible to code in the same process and to child processes started afterwards, but not to the parent shell and not to other programs. When the process exits, the change is gone.
Environment.SetEnvironmentVariable("APP_MODE", "debug");
Console.WriteLine(Environment.GetEnvironmentVariable("APP_MODE"));
// pass null to delete the variable
Environment.SetEnvironmentVariable("APP_MODE", null);
Console.WriteLine(Environment.GetEnvironmentVariable("APP_MODE") ?? "(deleted)");
debug
(deleted)
Use null to delete. On .NET Framework and older .NET versions an empty string also deleted the variable; modern .NET keeps it as a variable with an empty value.
User and machine variables (Windows)
An overload takes an EnvironmentVariableTarget:
| Target | Where it lives | Platforms |
|---|---|---|
Process (default) |
the current process | all |
User |
HKEY_CURRENT_USER\Environment registry key |
Windows only |
Machine |
HKEY_LOCAL_MACHINE\...\Session Manager\Environment |
Windows only, needs admin to write |
// read the persistent, per-user PATH (not the merged PATH of this process)
string? userPath = Environment.GetEnvironmentVariable(
"Path", EnvironmentVariableTarget.User);
// persist a variable for the current user; new processes will see it
Environment.SetEnvironmentVariable(
"MYTOOL_HOME", @"C:\tools\mytool", EnvironmentVariableTarget.User);
Persistent changes don't affect processes that are already running, including the terminal you launched the program from. You need to open a new terminal to see them. On Linux and macOS, User and Machine are not supported: reads return null and writes are silently ignored. There, persistent variables are configured in shell profiles (~/.bashrc, /etc/environment), systemd unit files or container definitions.
Expanding %VAR% references
ExpandEnvironmentVariables replaces %NAME% placeholders with their values. Unknown names are left untouched:
Environment.SetEnvironmentVariable("GREETING", "hello");
string s = Environment.ExpandEnvironmentVariables("%GREETING%, world! %UNDEFINED_X%");
Console.WriteLine(s);
hello, world! %UNDEFINED_X%
This uses Windows-style %NAME% syntax on every platform. Shell-style $NAME is not expanded. It's handy for config values like %TEMP%\myapp\cache.
Environment for child processes
When you start another program with Process, it inherits a copy of your environment. ProcessStartInfo.Environment lets you add, change or remove variables for the child without touching your own process. See Running OS commands for more on Process.
using System.Diagnostics;
var psi = new ProcessStartInfo("cmd", "/c echo %GREETING% %CHILD_ONLY%")
{
RedirectStandardOutput = true,
};
psi.Environment["CHILD_ONLY"] = "secret"; // add for the child only
psi.Environment.Remove("GREETING"); // hide from the child
using var p = Process.Start(psi)!;
Console.WriteLine(p.StandardOutput.ReadToEnd().Trim());
p.WaitForExit();
Console.WriteLine(Environment.GetEnvironmentVariable("CHILD_ONLY") ?? "(not set in parent)");
%GREETING% secret
(not set in parent)
psi.Environment starts as a copy of the current process environment, so you only need to specify the differences. On Linux use new ProcessStartInfo("sh", "-c \"echo $CHILD_ONLY\"") instead of cmd.
Prefer Environment properties for well-known values
Many values you might be tempted to read from environment variables have portable APIs:
Console.WriteLine(Environment.MachineName);
Console.WriteLine(Environment.UserName);
Console.WriteLine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile));
Console.WriteLine(Path.GetTempPath());
Console.WriteLine(Environment.ProcessorCount);
DESKTOP-1
kjk
C:\Users\kjk
C:\Users\kjk\AppData\Local\Temp\
16
Environment.SpecialFolder.UserProfile works on all platforms, while USERPROFILE exists only on Windows and HOME only on Unix. When you do need PATH, split it with Path.PathSeparator (; on Windows, : on Unix):
string[] dirs = (Environment.GetEnvironmentVariable("PATH") ?? "")
.Split(Path.PathSeparator, StringSplitOptions.RemoveEmptyEntries);
Environment variables with Microsoft.Extensions.Configuration
In ASP.NET Core and Generic Host apps you rarely call GetEnvironmentVariable directly. The configuration system merges appsettings.json, environment variables, command-line arguments and other sources into one IConfiguration, and environment variables override the JSON files.
Host.CreateApplicationBuilder and WebApplication.CreateBuilder add environment variables automatically. In a plain console app add the provider yourself:
dotnet add package Microsoft.Extensions.Configuration.EnvironmentVariables
dotnet add package Microsoft.Extensions.Configuration.Binder
Configuration keys are hierarchical and separated by : (Database:Host). Since : isn't allowed in variable names on every platform, use a double underscore __ in the variable name. It gets translated to :.
using Microsoft.Extensions.Configuration;
// normally set by the shell, Docker, Kubernetes etc.
Environment.SetEnvironmentVariable("MYAPP_Database__Host", "db.local");
Environment.SetEnvironmentVariable("MYAPP_Database__Port", "5433");
Environment.SetEnvironmentVariable("MYAPP_Hosts__0", "a.example.com");
Environment.SetEnvironmentVariable("MYAPP_Hosts__1", "b.example.com");
IConfiguration config = new ConfigurationBuilder()
.AddEnvironmentVariables(prefix: "MYAPP_") // only MYAPP_*, prefix is stripped
.Build();
Console.WriteLine(config["Database:Host"]);
Console.WriteLine(config.GetValue<int>("Database:Port"));
Console.WriteLine(config.GetValue("Database:Timeout", 30)); // default when missing
DbOptions db = config.GetSection("Database").Get<DbOptions>()!;
Console.WriteLine($"{db.Host}:{db.Port}");
string[] hosts = config.GetSection("Hosts").Get<string[]>()!;
Console.WriteLine(string.Join(", ", hosts));
class DbOptions
{
public string Host { get; set; } = "localhost";
public int Port { get; set; } = 5432;
}
db.local
5433
30
db.local:5433
a.example.com, b.example.com
Points to note:
- Key matching is case-insensitive, so
MYAPP_DATABASE__HOSTworks too. - Numeric segments (
Hosts__0,Hosts__1) bind to arrays and lists. - A prefix keeps your app from picking up unrelated variables. Without one, every variable becomes a configuration key.
- Connection strings follow a convention:
ConnectionStrings__Defaultis read withconfig.GetConnectionString("Default").
The Dependency Injection article shows how to inject such settings as options into services.
DOTNET_ENVIRONMENT and ASPNETCORE_ENVIRONMENT
The hosting environment name (Development, Staging, Production) comes from an environment variable: DOTNET_ENVIRONMENT for the Generic Host, and DOTNET_ENVIRONMENT or ASPNETCORE_ENVIRONMENT for web apps (with WebApplication.CreateBuilder, DOTNET_ENVIRONMENT wins if both are set). It defaults to Production and decides which appsettings.{Environment}.json file is loaded:
# bash
ASPNETCORE_ENVIRONMENT=Development dotnet run
# PowerShell
$env:ASPNETCORE_ENVIRONMENT = "Development"; dotnet run
var builder = WebApplication.CreateBuilder(args);
Console.WriteLine(builder.Environment.EnvironmentName); // Development
if (builder.Environment.IsDevelopment())
{
// enable developer exception page, Swagger etc.
}
During development, Properties/launchSettings.json sets variables for dotnet run and Visual Studio, so you don't have to set them in the shell:
{
"profiles": {
"MyApp": {
"commandName": "Project",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development",
"MYAPP_Database__Host": "localhost"
}
}
}
}
launchSettings.json is only used by development tooling. It's ignored when the published app runs.
Loading a .env file
Many projects keep local development settings in a .env file (git-ignored) instead of setting them in the shell. Packages like DotNetEnv handle the full format, but a minimal loader is short:
# .env
DB_HOST=localhost
DB_PASSWORD="p@ss word"
export API_URL=http://localhost:5000
DotEnv.Load(".env");
Console.WriteLine(Environment.GetEnvironmentVariable("DB_HOST"));
Console.WriteLine(Environment.GetEnvironmentVariable("DB_PASSWORD"));
Console.WriteLine(Environment.GetEnvironmentVariable("API_URL"));
static class DotEnv
{
public static void Load(string path, bool overwrite = false)
{
if (!File.Exists(path)) return;
foreach (string raw in File.ReadLines(path))
{
string line = raw.Trim();
if (line.Length == 0 || line.StartsWith('#')) continue;
if (line.StartsWith("export ")) line = line["export ".Length..];
int eq = line.IndexOf('=');
if (eq <= 0) continue;
string key = line[..eq].Trim();
string value = line[(eq + 1)..].Trim();
if (value.Length >= 2 && (value[0] == '"' || value[0] == '\'') && value[^1] == value[0])
value = value[1..^1];
// real environment wins over the file unless overwrite is requested
if (overwrite || Environment.GetEnvironmentVariable(key) is null)
Environment.SetEnvironmentVariable(key, value);
}
}
}
localhost
p@ss word
http://localhost:5000
Call DotEnv.Load at the very start of Main, before building configuration, so the configuration providers see the values.
Temporarily setting variables in tests
Because environment variables are process-wide, tests that change them should restore the previous value. A small IDisposable makes that automatic:
using (new TempEnv("FEATURE_X", "on"))
{
Console.WriteLine(Environment.GetEnvironmentVariable("FEATURE_X"));
}
Console.WriteLine(Environment.GetEnvironmentVariable("FEATURE_X") ?? "(unset)");
sealed class TempEnv : IDisposable
{
private readonly string _name;
private readonly string? _old;
public TempEnv(string name, string? value)
{
_name = name;
_old = Environment.GetEnvironmentVariable(name);
Environment.SetEnvironmentVariable(name, value);
}
public void Dispose() => Environment.SetEnvironmentVariable(_name, _old);
}
on
(unset)
Test frameworks like xUnit run test classes in parallel, and since there is only one environment per process, tests that modify the same variables must not run concurrently. A better design is to read environment variables in one place at startup and pass the resulting values (or an IConfiguration) to the rest of the code, which can then be tested without touching the real environment.
Tips
- Read once, at startup. Parse and validate all variables into a settings object when the program starts, and fail with a clear message if something required is missing.
- Don't log secrets. Dumping all environment variables to logs leaks API keys and passwords. Log only the names, or mask the values.
- Environment variables aren't a vault. Any code in the process can read them, and they may show up in crash dumps,
docker inspector/proc/<pid>/environ. For production secrets prefer a secret manager (Azure Key Vault, AWS Secrets Manager, Kubernetes secrets). In development, usedotnet user-secrets. - Use a prefix like
MYAPP_for your own variables to avoid collisions with system and tool variables. - Mind the platform. Names are case-sensitive on Unix,
User/Machinetargets are Windows-only, andPATHuses different separators on different platforms.