dotenv.net is a zero-dependency module that loads environment variables from a .env environment variable file into System.Environment
. Please feel free to create issues with feature requests and raise bugs there too.
Big ups to those who have contributed to this library. 👏
@bolorundurowb @joliveros @vizeke @merqlove
First install the library as a dependency in your application from nuget
Install-Package dotenv.net
or
dotnet add package dotenv.net
or for paket
paket add dotenv.net
Create a file with no filename and an extension of .env
.
A sample .env
file would look like this:
DB_HOST=localhost
DB_USER=root
DB_PASS=s1mpl3
in the Startup.cs
file or as early as possible in your code add the following:
using DotEnv;
...
DotEnv.Config();
the values saved in your .env
file would be avaibale in your application and can be accessed via
Environment.GetEnvironmentVariable("DB_HOST"); // would output 'localhost'
If using with ASP.NET Core or any other system that uses IServiceCollection
for its dependency injection, in the Startup.cs
file
public void ConfigureServices(IServiceCollection services)
{
...
// configure dotenv
services.AddEnv(builder => {
builder
.AddEnvFile("/custom/path/to/your/env/vars")
.AddThrowOnError(false)
.AddEncoding(Encoding.ASCII);
});
}
With this, your application would have the env file variables imported.
Default: true
You can specify if you want the library to error out if any issue arises or fail silently.
DotEnv.Config(false); //fails silently
Default: .env
You can specify a custom path if your file containing environment variables is named or located differently.
DotEnv.Config(true, "/custom/path/to/your/env/vars");
Default: Encoding.Default
You may specify the encoding of your file containing environment variables using this option.
DotEnv.Config(true, ".env", Encoding.Unicode);