This project demonstrates loading environment variables from a .env file using DotNetEnv and Microsoft.Extensions.Configuration.
.env: Key-value pairs for environment variables (e.g.,WelcomeMessage,EnvironmentMessage).DotNetEnvFilesSupport.cs: Sample program that:- Loads
.envwithDotNetEnv.Env.Load. - Reads values via
DotNetEnv.Env.GetString. - Reads variables via
Environment.GetEnvironmentVariable. - Adds
.envto configuration withConfigurationBuilder.AddDotNetEnv. - Shows parsing without setting env vars via
DotNetEnv.Env.NoEnvVars().Load.
- Loads
global.json: Pins the .NET SDK version.
- .NET SDK specified in
global.json. - NuGet package:
DotNetEnv(version declared in source).
- Create a
.envfile in this folder:WelcomeMessage="Hello, World!" EnvironmentMessage="This is a sample .env file."
From this folder (DotEnv), run:
dotnet run DotNetEnvFilesSupport.csIf you have a full project file later, you can run:
dotnet run- Prints:
- Welcome message from
Env.GetString. EnvironmentMessageviaEnvironment.GetEnvironmentVariable.WelcomeMessagevia configuration.- All parsed key-value pairs from
.envwhen usingNoEnvVars().Load().
- Welcome message from
AddDotNetEnv(".env", LoadOptions.TraversePath())allows traversing parent directories to locate.env.NoEnvVars()prevents values from being injected into the process environment; use it for parsing only.