DEV Community

Cover image for Reading .env Files in C#
Ricardo
Ricardo

Posted on • Originally published at rmauro.dev on

Reading .env Files in C#

In C#, managing application configuration using environment variables stored in a .env file is a best practice, especially for handling different environments like development, staging, and production.

A .env file is a convenient way to store these variables locally during development.

In this post, let's check how to read a .env file in a C# application without relying on any third-party libraries. In Fact it's pretty simple to do.

Why Use a .env File?

A .env file contains key-value pairs representing environment variables.

It helps in keeping configuration separate from the codebase and is especially useful for.

  • Security: Sensitive information like API keys can be excluded from the codebase.
  • Consistency: Ensures that configuration is consistent across different environments.
  • Convenience: Easy to switch between different configurations during development.

Setting Up the Project

Let's start with a simple .NET console application.

dotnet new console -n EnvReaderApp
cd EnvReaderApp
Enter fullscreen mode Exit fullscreen mode

Create a .env file in the root of your project directory.

# .env
API_KEY=12345
DATABASE_URL=localhost:5432
DEBUG=true
Enter fullscreen mode Exit fullscreen mode

Implementing the .env File Reader

Let's implement a simple parser that reads the .env file and sets the variables as environment variables in the application.

using System;
using System.IO;

class EnvReader
{
    public static void Load(string filePath)
    {
        if (!File.Exists(filePath))
            throw new FileNotFoundException($"The file '{filePath}' does not exist.");

        foreach (var line in File.ReadAllLines(filePath))
        {
            if (string.IsNullOrWhiteSpace(line) || line.StartsWith("#"))
                continue; // Skip empty lines and comments

            var parts = line.Split('=', 2);
            if (parts.Length != 2)
                continue; // Skip lines that are not key-value pairs

            var key = parts[0].Trim();
            var value = parts[1].Trim();
            Environment.SetEnvironmentVariable(key, value);
        }
    }
}

Enter fullscreen mode Exit fullscreen mode

Let's use the EnvReader in our project.

static void Main(string[] args)
{
    // Load environment variables from .env file
    EnvReader.Load(".env");

    // Access the environment variables
    string apiKey = Environment.GetEnvironmentVariable("API_KEY");
    string databaseUrl = Environment.GetEnvironmentVariable("DATABASE_URL");
    string debug = Environment.GetEnvironmentVariable("DEBUG");

    // Output the values
    Console.WriteLine($"API Key: {apiKey}");
    Console.WriteLine($"Database URL: {databaseUrl}");
    Console.WriteLine($"Debug Mode: {debug}");

    // Check if debug mode is enabled
    if (bool.TryParse(debug, out bool isDebug) && isDebug)
    {
        Console.WriteLine("Debug mode is enabled.");
    }
    else
    {
        Console.WriteLine("Debug mode is not enabled.");
    }
}

Enter fullscreen mode Exit fullscreen mode

How It Works

  1. Reading the .env File: The Load method reads all lines from the .env file.
  2. Processing Each Line: It skips empty lines and comments, splits the line into key and value, and sets them as environment variables using Environment.SetEnvironmentVariable.
  3. Using Environment Variables: The Main method demonstrates accessing these variables and using them in the application logic.

Best Practices

  1. Security: Add the .env file to your .gitignore file to avoid committing sensitive information.
  2. Template Files: Use a .env.example file with placeholder values to share configuration requirements without exposing sensitive data.
  3. Error Handling: Implement robust error handling for scenarios like missing files or incorrect formats.

Conclusion

Reading a .env file in C# without third-party libraries is straightforward and allows you to manage configuration securely and efficiently.

This approach gives you complete control over how you handle and parse environment variables, which can be tailored to fit specific needs or constraints.

Feel free to enhance this solution by adding features like default values, nested configuration, or more sophisticated parsing logic. Happy coding! ๐Ÿ˜Ž

Top comments (1)

Collapse
 
pprometey profile image
Alex Chernyavskiy

Read the documentation. The .net platform has a great tool for working with sensitive data so that it does not end up in a .git repository. Using a .env file for this is an anti-pattern. And complicating the logic. I do not see a single advantage of the method you proposed over standard .net mechanisms. This is called - Over-engineered.
learn.microsoft.com/en-us/aspnet/c...