Environment Variables in C#
Environment.GetEnvironmentVariable and IConfiguration
Reading Environment Variables
In C# and .NET, environment variables are accessed throughEnvironment.GetEnvironmentVariable():
text
string? dbUrl = Environment.GetEnvironmentVariable("DATABASE_URL");
string port = Environment.GetEnvironmentVariable("PORT") ?? "3000";Setting Environment Variables
text
Environment.SetEnvironmentVariable("MY_VAR", "value");Popular Libraries
ASP.NET Core Configuration provides IConfiguration which reads from environment variables, JSON files, command-line arguments, and other sources with layered precedence. Environment variables prefixed with the app name override other sources.
DotNetEnv provides .env file support for .NET applications.
Common Gotchas
- In ASP.NET Core, environment variables with double underscores (
__) map to nested configuration keys.ConnectionStrings__DefaultbecomesConnectionStrings:Default. ASPNETCORE_ENVIRONMENTcontrols the hosting environment (Development, Staging, Production) and affects whichappsettings.*.jsonfile is loaded.- Use
IConfigurationand dependency injection rather than readingEnvironment.GetEnvironmentVariabledirectly in application code.