Skip to content

Instantly share code, notes, and snippets.

@0x49D1
Last active March 30, 2022 12:41
Show Gist options
  • Save 0x49D1/89aac0f4c3dc8fa076ae3655372ba83a to your computer and use it in GitHub Desktop.
Save 0x49D1/89aac0f4c3dc8fa076ae3655372ba83a to your computer and use it in GitHub Desktop.
.env Loader class for >.NET 5 or .NET Core
// credits to: https://dusted.codes/dotenv-in-dotnet
// To read add something like:
// public static class Program
// {
// public static async Task Main(string[] args)
// {
// var root = Directory.GetCurrentDirectory();
// var dotenv = Path.Combine(root, ".env");
// DotEnv.Load(dotenv);
// // Other code
// }
// }
public static class DotEnv
{
public static void Load(string filePath)
{
if (!File.Exists(filePath))
return;
foreach (var line in File.ReadAllLines(filePath))
{
var parts = line.Split(
'=',
StringSplitOptions.RemoveEmptyEntries);
if (parts.Length != 2)
continue;
Environment.SetEnvironmentVariable(parts[0], parts[1]);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment