DotNetEnv Documentation

repository·master·Indexed 20 days ago

https://github.com/tonerdo/dotnet-env

A .NET library for loading and managing environment variables from .env files. It provides features for traversing parent directories, type-safe retrieval helpers, integration with .NET ConfigurationBuilder, and support for advanced interpolation, quoting rules, and byte codes.

Tokens
1.5K
Snippets
5
Records
6
Agent score
19%

What's inside DotNetEnv

  1. Understand .env file structure and interpolation

    master

    The .env file supports standard assignments, comments, and advanced interpolation.

    Assignments and Comments

    • KEY=value
    • Comments can be at the end of a line: KEY=value # comment
    • A # immediately following = is treated as a comment: KEY=#comment
    • Unquoted values can include # if it is not the first character after the value: KEY=value#notcomment #actualcomment

    Interpolation Syntax

    Interpolation supports default, required, and alternative values:

    • Default value: ${ENVVAR:-default} or ${ENVVAR-default}
    • Required (exit with error if empty): ${ENVVAR:?error} or ${ENVVAR?error}
    • Alternative (use if set): ${ENVVAR:+alternative}

    Interpolation can be nested, e.g., ${VARIABLE:-${FOO:-default}}.

    Quoting Rules

    • Double quotes (""): Supports interpolation, whitespace, escaped characters, and byte codes.
    • Single quotes (''): Supports whitespace, but no interpolation, escaped characters, or byte codes. Use this for truly raw values.
    • Unquoted: Supports interpolation and inline whitespace, but no quote characters, escaped characters, or byte codes.

    Byte Codes (Double Quotes Only)

    You can declare Unicode characters using hex codes:

    • UTF8: "\xF0\x9F\x9A\x80" (🚀)
    • UTF16: "\uae" (®)
    • UTF32: "\U1F680" (🚀)
  2. Install DotNetEnv via NuGet or .NET CLI

    master

    You can install DotNetEnv using the Visual Studio Package Manager or the .NET Core CLI.

    Visual Studio:

    PM> Install-Package DotNetEnv

    ** .NET Core CLI:**

    dotnet add package DotNetEnv
    PM> Install-Package DotNetEnv
    
    dotnet add package DotNetEnv
  3. Configure Load behavior with LoadOptions or Fluent Syntax

    master

    You can control how .env files are parsed and applied using LoadOptions or the recommended fluent syntax.

    Key Options:

    • setEnvVars: If false, the library processes the file but does not update System.Environment. Use NoEnvVars() to set this.
    • clobberExistingVars: If false, existing environment variables will not be overwritten. Use NoClobber() to set this.
    • onlyExactPath: If true, the library only looks at the specific path provided and does not traverse parent directories. Use TraversePath() to enable traversal.

    Example: Loading without updating environment variables If you only want to read the file into a dictionary without affecting the process environment, use NoEnvVars() and ToDotEnvDictionary():

    var dict = DotNetEnv.Env.NoEnvVars().Load().ToDotEnvDictionary();
    // Using LoadOptions object
    new DotNetEnv.LoadOptions(
        setEnvVars: true,
        clobberExistingVars: true,
        onlyExactPath: true
    )
    
    // Recommended fluent syntax
    DotNetEnv.Env.NoEnvVars().NoClobber().TraversePath().Load();
    
    // Load into a dictionary without setting environment variables
    var dict = DotNetEnv.Env.NoEnvVars().Load().ToDotEnvDictionary();
    
    // Load without overwriting existing environment variables
    DotNetEnv.Env.NoClobber().Load();
    
    // Search parent directories for .env
    DotNetEnv.Env.TraversePath().Load();
  4. Integrate DotNetEnv with .NET ConfigurationBuilder

    master

    You can add .env files as a source to the standard .NET ConfigurationBuilder. The provider automatically maps __ to : to support configuration sections.

    var configuration = new ConfigurationBuilder()
        .AddDotNetEnv(".env", LoadOptions.TraversePath())
        .Build();
    var configuration = new ConfigurationBuilder()
        .AddDotNetEnv(".env", LoadOptions.TraversePath())
        .Build();
  5. Load .env files into environment variables

    master

    Use DotNetEnv.Env.Load() to automatically look for a .env file in the current directory.

    To search for a .env file in the current or any parent/ancestor directory, use TraversePath().

    You can also specify a direct path, or load from a Stream, a string, or multiple files.

    Note on LoadMulti: When loading multiple files, values in later files will overwrite values in earlier files unless NoClobber() is used.

    DotNetEnv.Env.Load();
    DotNetEnv.Env.TraversePath().Load();
    DotNetEnv.Env.Load("./path/to/.env");
    
    using (var stream = File.OpenRead("./path/to/.env"))
    {
        DotNetEnv.Env.Load(stream);
    }
    
    DotNetEnv.Env.LoadContents("OK=GOOD\nTEST=\"more stuff\"");
    
    DotNetEnv.Env.LoadMulti(new[] {
        ".env",
        ".env2",
    });
  6. Access environment variables using DotNetEnv helpers

    master

    Once loaded, variables can be accessed via the standard System.Environment.GetEnvironmentVariable method, or through DotNetEnv helper methods which provide type-safe retrieval and default values.

    Helper Methods:

    • GetString(key, [defaultValue])
    • GetBool(key, [defaultValue])
    • GetInt(key, [defaultValue])
    • GetDouble(key, [defaultValue])
    System.Environment.GetEnvironmentVariable("IP");
    
    DotNetEnv.Env.GetString("A_STRING");
    DotNetEnv.Env.GetBool("A_BOOL");
    DotNetEnv.Env.GetInt("AN_INT");
    DotNetEnv.Env.GetDouble("A_DOUBLE");
    
    // With a default value if not found
    DotNetEnv.Env.GetString("THIS_DOES_NOT_EXIST", "Variable not found");