/dotenv.net

A library to read .env files in a .NET Core environment

Primary LanguageC#MIT LicenseMIT

dotenv.net

CircleCI NuGet Badge License: MIT Book session on Codementor

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.

Contributors

Big ups to those who have contributed to this library. 👏

@bolorundurowb @joliveros @vizeke @merqlove

Usage

Conventional

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'

Using with DI (IServiceCollection)

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.

Options

ThrowError

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

Path

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");

Encoding

Default: Encoding.Default

You may specify the encoding of your file containing environment variables using this option.

DotEnv.Config(true, ".env", Encoding.Unicode);