A .NET library to load environment variables from .env files. Supports .NET Core and .NET Framework (4.6+).
Available on NuGet
Visual Studio:
PM> Install-Package DotNetEnv
.NET Core CLI:
dotnet add package DotNetEnv
Load()
will automatically look for a .env
file in the current directory by default,
or any higher parent/ancestor directory if given the option flag via TraversePath()
DotNetEnv.Env.Load();
DotNetEnv.Env.TraversePath().Load();
Or you can specify the path directly to the .env
file,
and as above, with TraversePath()
, it will start looking there
and then look in higher dirs from there if not found.
DotNetEnv.Env.Load("./path/to/.env");
It's also possible to load the (text) file as a Stream
or string
or multiple files in sequence
using (var stream = File.OpenRead("./path/to/.env"))
{
DotNetEnv.Env.Load(stream);
}
DotNetEnv.Env.LoadContents("OK=GOOD\nTEST=\"more stuff\"");
// will use values in later files over values in earlier files
// NOTE: NoClobber will reverse this, it will use the first value encountered!
DotNetEnv.Env.LoadMulti(new[] {
".env",
".env2",
});
The variables in the .env
can then be accessed through the System.Environment
class
System.Environment.GetEnvironmentVariable("IP");
Or through one of the helper methods:
DotNetEnv.Env.GetString("A_STRING");
DotNetEnv.Env.GetBool("A_BOOL");
DotNetEnv.Env.GetInt("AN_INT");
DotNetEnv.Env.GetDouble("A_DOUBLE");
The helper methods also have an optional second argument which specifies what value to return if the variable is not found:
DotNetEnv.Env.GetString("THIS_DOES_NOT_EXIST", "Variable not found");
You can also pass a LoadOptions
object arg to all DotNetEnv.Env.Load
variants to affect the Load/Parse behavior:
new DotNetEnv.LoadOptions( setEnvVars: true, clobberExistingVars: true, onlyExactPath: true )