EasyReasy.EnvironmentVariables 1.2.1

dotnet add package EasyReasy.EnvironmentVariables --version 1.2.1
                    
NuGet\Install-Package EasyReasy.EnvironmentVariables -Version 1.2.1
                    
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="EasyReasy.EnvironmentVariables" Version="1.2.1" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="EasyReasy.EnvironmentVariables" Version="1.2.1" />
                    
Directory.Packages.props
<PackageReference Include="EasyReasy.EnvironmentVariables" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add EasyReasy.EnvironmentVariables --version 1.2.1
                    
#r "nuget: EasyReasy.EnvironmentVariables, 1.2.1"
                    
#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.
#:package EasyReasy.EnvironmentVariables@1.2.1
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=EasyReasy.EnvironmentVariables&version=1.2.1
                    
Install as a Cake Addin
#tool nuget:?package=EasyReasy.EnvironmentVariables&version=1.2.1
                    
Install as a Cake Tool

EasyReasy.EnvironmentVariables

← Back to EasyReasy System

NuGet

A lightweight .NET library for environment variable validation and management with startup-time safety.

Overview

EasyReasy.EnvironmentVariable provides a structured way to define, validate, and retrieve environment variables with early error detection and type safety.

Why Use EasyReasy.EnvironmentVariable?

  • Startup-time safety: Environment variable names are defined as constants and validated at startup
  • Early validation: Catch missing variables at startup, not during execution
  • Clear error messages: Detailed feedback about what's missing or invalid
  • Type safety: Strongly typed environment variable access with IntelliSense support, making it easy to find and get suggestions for available environment variables
  • Static analysis: Compiler can find all references to environment variables, making it easy to see where each variable is used and identify unused variables
  • Minimum length validation: Ensure variables meet length requirements for both security and validation purposes (empty strings are never valid)

Core Features

Environment Variable Validation

Define your environment variables in configuration classes and validate them at startup:

[EnvironmentVariableNameContainer]
public static class EnvironmentVariable
{
    [EnvironmentVariableName(minLength: 10)]
    public static readonly VariableName DatabaseUrl = new VariableName("DATABASE_URL");
    
    [EnvironmentVariableName(minLength: 20)]
    public static readonly VariableName ApiKey = new VariableName("API_KEY");
    
    [EnvironmentVariableName]
    public static readonly VariableName DebugMode = new VariableName("DEBUG_MODE");
}

Startup Validation

Validate all environment variables at application startup:

// In Program.cs or Startup.cs
EnvironmentVariableHelper.ValidateVariableNamesIn(typeof(EnvironmentVariable));

This validates all environment variables defined in the EnvironmentVariable class. You can pass any number of configuration classes, but it's recommended to use only one to keep all environment variable definitions in one place.

This will throw an InvalidOperationException with detailed error messages if any required environment variables are missing or don't meet minimum length requirements.

Safe Environment Variable Retrieval

Get environment variables with built-in validation:

string databaseUrl = EnvironmentVariable.DatabaseUrl.GetValue(minLength: 10);
string apiKey = EnvironmentVariable.ApiKey.GetValue();

Note: The GetValue() method is an extension method for VariableName that internally calls EnvironmentVariableHelper.GetVariableValue. If you prefer, you can also call EnvironmentVariableHelper.GetVariableValue(EnvironmentVariable.DatabaseUrl, minLength: 10) directly.

Environment Variable Ranges

You can declare a range of environment variables that share a common prefix. This is useful for cases like multiple file paths, API keys, etc.

[EnvironmentVariableNameContainer]
public static class EnvironmentVariable
{
    // This declares a range of names (use with VariableNameRange)
    [EnvironmentVariableNameRange(minCount: 2)]
    public static readonly VariableNameRange FilePaths = new VariableNameRange("FILE_PATH");

    // "Normal" variable names can also exist in the same file
    [EnvironmentVariableName(minLength: 10)]
    public static readonly VariableName DatabaseUrl = new VariableName("DATABASE_URL");
}

This will match all environment variables whose names start with FILE_PATH (e.g., FILE_PATH1, FILE_PATH_A, FILE_PATH_01, etc.).

Both [EnvironmentVariableNameRange] and [EnvironmentVariableName] can of course be used in the same file. Just make sure to use the correct types (VariableNameRange for the ranges and VariableName for the normal names).

Retrieving All Values in a Range

You can retrieve all values for a range using either the helper or the extension method:

List<string> filePaths = EnvironmentVariableHelper.GetAllVariableValuesInRange(EnvironmentVariable.FilePaths);
// or
List<string> filePaths = EnvironmentVariable.FilePaths.GetAllValues();
Validation

If you specify minCount in the attribute, validation will ensure at least that many variables with the prefix are present and non-empty. If not, a clear error message will be thrown at startup.

Loading from Files

Load environment variables from .env files and set them in the running program:

EnvironmentVariableHelper.LoadVariablesFromFile("config.env");

File format:

DATABASE_URL=postgresql://localhost:5432/mydb
API_KEY=my-secret-key
DEBUG_MODE=true
FILE_PATH1=/path/to/file1
FILE_PATH2=/path/to/file2
# Comments are supported

Note: This is particularly useful in unit tests where environment variables need to be configured for testing but can't be in the code, and there's no launchSettings.json file or built-in way like ASP.NET Core web API applications have.

Loading from Strings and Streams

You can also load environment variables from strings or streams:

// Load from a string
string configContent = @"DATABASE_URL=postgresql://localhost:5432/mydb
API_KEY=my-secret-key";
EnvironmentVariableHelper.LoadVariablesFromString(configContent);

// Load from a stream
using Stream stream = File.OpenRead("config.env");
EnvironmentVariableHelper.LoadVariablesFromStream(stream);

Loading from Linux systemd Service Files

Load environment variables from Linux systemd service files using the built-in preprocessor:

// Load from a systemd service file
EnvironmentVariableHelper.LoadVariablesFromFile("/etc/systemd/system/myapp.service", new SystemdServiceFilePreprocessor());

// Or load from a string containing systemd service content
string systemdContent = @"[Service]
Environment=ASPNETCORE_ENVIRONMENT=Production
Environment=ASPNETCORE_URLS=http://localhost:5002
Environment=BYTESHELF_STORAGE_PATH=/mnt/ssd1/byte-shelf/storage
ExecStart=/usr/bin/myapp";
EnvironmentVariableHelper.LoadVariablesFromString(systemdContent, new SystemdServiceFilePreprocessor());

The SystemdServiceFilePreprocessor extracts all Environment= lines from the service file and converts them to standard environment variable format. It supports:

  • Standard systemd Environment=KEY=value format
  • Comments and other systemd directives are automatically ignored

Custom Preprocessors

You can create custom preprocessors by implementing the IFileContentPreprocessor interface:

public class MyCustomPreprocessor : IFileContentPreprocessor
{
    public string Preprocess(string content)
    {
        // Transform the content as needed
        return transformedContent;
    }
}

// Use your custom preprocessor
EnvironmentVariableHelper.LoadVariablesFromString(content, new MyCustomPreprocessor());
Product Compatible and additional computed target framework versions.
.NET net8.0 is compatible.  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.  net9.0 was computed.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.
  • net8.0

    • No dependencies.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.2.1 14 8/3/2025
1.2.0 12 8/3/2025
1.1.0 486 7/23/2025
1.0.0 179 7/20/2025