process.env.dev

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__Default becomes ConnectionStrings:Default.
  • ASPNETCORE_ENVIRONMENT controls the hosting environment (Development, Staging, Production) and affects which appsettings.*.json file is loaded.
  • Use IConfiguration and dependency injection rather than reading Environment.GetEnvironmentVariabledirectly in application code.