DotEnv.Core 2.1.0-alpha3

This is a prerelease version of DotEnv.Core.
There is a newer version of this package available.
See the version list below for details.
dotnet add package DotEnv.Core --version 2.1.0-alpha3
NuGet\Install-Package DotEnv.Core -Version 2.1.0-alpha3
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="DotEnv.Core" Version="2.1.0-alpha3" />
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add DotEnv.Core --version 2.1.0-alpha3
#r "nuget: DotEnv.Core, 2.1.0-alpha3"
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
// Install DotEnv.Core as a Cake Addin
#addin nuget:?package=DotEnv.Core&version=2.1.0-alpha3&prerelease

// Install DotEnv.Core as a Cake Tool
#tool nuget:?package=DotEnv.Core&version=2.1.0-alpha3&prerelease

dotenv.core

dotenv-logo

dotenv.core dotenv.core dotenv.core Nuget-Badges

dotenv.core is a class library for read and parsing .env files in .NET Core and also provides a mechanism to retrieve the value of an environment variable in a simple and easy way.

The advantage of using this library is that you do not need to set the environment variable from the operating system shell (dotenv sets environment variables from a .env file).

Features

  • It has a fluent interface, which makes it simple and easy to use.
  • Support for load multiple .env files.
  • Support to load the .env file depending on the environment (development, test, staging, or production).
  • Searches in parent directories when it does not find the .env file in the current directory.
  • You can set the base path for a set of .env files.
  • You can define which keys should be required by the application.
  • You can change the default .env file name, so it does not necessarily have to be .env.
  • Support for the variables interpolation.
  • And much more.

Don't forget to visit the official library website where you can find API documentation, articles and diagrams.

Basic Concepts

What is a .env file?

A .env file or dotenv file is a simple text configuration file for controlling your Applications environment constants.

What do .env files look like?

.env files are line delimitated text files, meaning that each new line represents a single variable. By convention .env variable names are uppercase words separated by underscores. Variable names are followed directly by an = which, in turn is followed directly by the value, for example:

VARIABLE_NAME=value

What is environment variable?

An environment variable is a dynamic variable that can affect the behavior of running processes on a computer. They are part of the environment in which a process runs.

Installation

If you're an hardcore and want to do it manually, you must add the following to the csproj file:

<PackageReference Include="DotEnv.Core" Version="2.0.1" />

If you're want to install the package from Visual Studio, you must open the project/solution in Visual Studio, and open the console using the Tools > NuGet Package Manager > Package Manager Console command and run the install command:

Install-Package DotEnv.Core

If you are making use of the dotnet CLI, then run the following in your terminal:

dotnet add package DotEnv.Core

Overview

Load .env file

You must import the namespace types at the beginning of your class file:

using DotEnv.Core;

Then you can load the .env file with the Load method of the EnvLoader class:

new EnvLoader().Load();

By default, the Load method will search for a file called .env in the current directory and if it does not find it, it will search for it in the parent directories of the current directory. Generally, the current directory is where the executable (your application itself) with its dependencies is located.

Remember that if no encoding is specified to the Load method, the default will be UTF-8. Also, by default, the Load method does not overwrite the value of an existing environment variable.

You can also load your own .env file using the AddEnvFile method:

new EnvLoader()
   .AddEnvFile("config.env")
   .Load();

In this case, the Load method will search for a file called config.env instead of .env.

Accessing environment variables

After you have loaded the .env file with the Load method, you can access the environment variables using the indexer of the EnvReader class:

var reader = new EnvReader();
string key1 = reader["KEY1"];
string key2 = reader["KEY2"];

Or you can also access the environment variables using the static property Instance:

string key1 = EnvReader.Instance["KEY1"];
string key2 = EnvReader.Instance["KEY2"];

If you don't want to use the EnvReader class to access environment variables, you can use the System.Environment class:

string key1 = System.Environment.GetEnvironmentVariable("KEY1");
string key2 = System.Environment.GetEnvironmentVariable("KEY2");

Load .env file without altering the environment

You can load an .env file without having to modify the environment:

var envVars = new EnvLoader()
        .AvoidModifyEnvironment()
        .Load();

string key1 = envVars["KEY1"];
string key2 = envVars["KEY2"];

The Load method will return an instance that implements the IEnvironmentVariablesProvider interface and through this instance we can access the environment variables. In fact, the environment variables are obtained from a dictionary, instead of the current process.

Required Keys

You can specify which keys should be required by the application, in case they are missing, throw an error:

new EnvValidator()
    .SetRequiredKeys("SERVICE_APP_ID", "SERVICE_KEY", "SERVICE_SECRET")
    .Validate();

The Validate method will check if the keys "SERVICE_APP_ID", "SERVICE_KEY", "SERVICE_SECRET" are present in the application, otherwise it throws an exception.

Load .env file based on environment

You can load an .env file based on the environment (dev, test, staging or production) with the LoadEnv method. The environment is defined by the actual environment variable as DOTNET_ENV:

new EnvLoader().LoadEnv();

The LoadEnv method will search for these .env files in the following order:

  • .env.[environment].local (has the highest priority)
  • .env.local
  • .env.[environment]
  • .env (has the lowest priority)

The environment is specified by the actual environment variable DOTNET_ENV.

It should be noted that the default environment will be development or dev if the environment is never specified with DOTNET_ENV.

Parsing .env files

You can analyze key-value pairs from any data source (a .env file, a database, a web service, etc):

string myDataSource = @"
    SERVICE_APP_ID=1
    SERVICE_KEY=1234$
    SERVICE_SECRET=1234example$
";
new EnvParser().Parse(myDataSource);

Then you can access the environment variables with the EnvReader or System.Environment class.

Using DotEnv in ASP.NET Core

Open the Startup.cs file and add this code in the constructor:

new EnvLoader().Load();
Configuration = new ConfigurationBuilder()
          .AddEnvironmentVariables()
          .Build();

Once the environment variables have been set from an .env file, we call the AddEnvironmentVariables method to take care of adding the environment variables in the configuration object managed by ASP.NET Core. Then, the keys can be accessed with the IConfiguration interface, for example:

class HomeController
{
    public HomeController(IConfiguration configuration)
    {
        string key = configuration["KEY_NAME"];
    }
}

If you are using ASP.NET Core 6, you will not need to add anything in a Startup.cs file. Simply go to Program.cs and add the following code after the WebApplication.CreateBuilder method:

new EnvLoader().Load();
builder.Configuration.AddEnvironmentVariables();

For more information, see the articles.

File Format

  • Empty lines or lines with white-spaces will be ignored.
  • The key-value format must be as follows: KEY=VAL.
  • There is no special handling of quotation marks. This means that they are part of the VAL.
  • If the value of a key is an empty string, it will be converted to a white-space.
  • White-spaces at both ends of the key and value are ignored.

Comments

Each line beginning with the # character is a comment. White-spaces at the beginning of each comment will be ignored.

Example:

# comment without white spaces
   # comment with white spaces
KEY=VALUE

Interpolating variables

Sometimes you will need to interpolate variables within a value, for example:

MYSQL_USER=root
MYSQL_ROOT_PASSWORD=1234
CONNECTION_STRING=username=${MYSQL_USER};password=${MYSQL_ROOT_PASSWORD};database=testdb;

If the variable embedded in the value is not set, the parser will throw an exception, for example:

MYSQL_ROOT_PASSWORD=1234
CONNECTION_STRING=username=${MYSQL_USER};password=${MYSQL_ROOT_PASSWORD};database=testdb;
MYSQL_USER=root

In the above example, the parser should throw an exception because the MYSQL_USER variable is not set.

Frequently Answered Questions

Can I use an .env file in a production environment?

Generally, you should not add sensitive data (such as passwords) to a .env file, as it would be unencrypted! Instead, you could use a secrets manager such as Azure Key Vault or AWS Secrets Manager.

If you are going to use .env files in production, make sure you have good security at the infrastructure level and also grant read/write permissions to a specific user (such as admin), so that not just anyone can access your .env file.

Should I commit my .env file?

Credentials should only be accessible on the machines that need access to them. Never commit sensitive information to a repository that is not needed by every development machine.

Why is it not overriding existing environment variables?

By default, it won't overwrite existing environment variables as dotenv assumes the deployment environment has more knowledge about configuration than the application does.

Contribution

If you want to contribute in this project, simply fork the repository, make changes (I recommend that you create your own branch) and then create a pull request.

Product Compatible and additional computed target framework versions.
.NET net5.0 was computed.  net5.0-windows was computed.  net6.0 was computed.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 was computed.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed. 
.NET Core netcoreapp2.0 was computed.  netcoreapp2.1 was computed.  netcoreapp2.2 was computed.  netcoreapp3.0 was computed.  netcoreapp3.1 was computed. 
.NET Standard netstandard2.0 is compatible.  netstandard2.1 was computed. 
.NET Framework net461 was computed.  net462 was computed.  net463 was computed.  net47 was computed.  net471 was computed.  net472 was computed.  net48 was computed.  net481 was computed. 
MonoAndroid monoandroid was computed. 
MonoMac monomac was computed. 
MonoTouch monotouch was computed. 
Tizen tizen40 was computed.  tizen60 was computed. 
Xamarin.iOS xamarinios was computed. 
Xamarin.Mac xamarinmac was computed. 
Xamarin.TVOS xamarintvos was computed. 
Xamarin.WatchOS xamarinwatchos was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.
  • .NETStandard 2.0

    • No dependencies.

NuGet packages (1)

Showing the top 1 NuGet packages that depend on DotEnv.Core:

Package Downloads
Dotenv.Extensions.Microsoft.DependencyInjection

Adds dotenv.core extensions for Microsoft.Extensions.DependencyInjection

GitHub repositories (1)

Showing the top 1 popular GitHub repositories that depend on DotEnv.Core:

Repository Stars
ose-net/yesql.net
YeSQL.NET is a class library for loading SQL statements from .sql files instead of writing SQL code in your C# source files
Version Downloads Last updated
3.0.0 33,224 5/3/2023
2.3.2 8,442 1/21/2023
2.3.1 1,316 11/24/2022
2.3.0 509 11/17/2022
2.2.1 1,348 7/4/2022
2.2.0 389 6/30/2022
2.1.0 395 5/30/2022
2.1.0-alpha3 132 5/13/2022
2.1.0-alpha2 149 5/10/2022
2.1.0-alpha1 140 5/5/2022
2.0.1 4,814 4/30/2022
2.0.0 412 3/29/2022
1.1.3 263 1/3/2022
1.1.2 227 12/31/2021
1.0.2 237 12/24/2021
1.0.1 258 12/18/2021
1.0.0 283 12/16/2021