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
Create a .env file in the root of your project directory.
# .env
API_KEY=12345
DATABASE_URL=localhost:5432
DEBUG=true
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); } }
}
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."); }
}
How It Works
-
Reading the .env File: The
Load
method reads all lines from the.env
file. -
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
. -
Using Environment Variables: The
Main
method demonstrates accessing these variables and using them in the application logic.
Best Practices
-
Security: Add the
.env
file to your.gitignore
file to avoid committing sensitive information. -
Template Files: Use a
.env.example
file with placeholder values to share configuration requirements without exposing sensitive data. - 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! 😎