Skip to content

Instantly share code, notes, and snippets.

@gleox
Created December 29, 2018 07:01
Show Gist options
  • Save gleox/9a1021cb8712e349a5f77d3764647488 to your computer and use it in GitHub Desktop.
Save gleox/9a1021cb8712e349a5f77d3764647488 to your computer and use it in GitHub Desktop.
DotEnvHelper.cs
using System;
using System.IO;
using System.Text;
using System.Threading;
namespace Utils
{
public class DotEnvHelper
{
private static int _initialized;
public static void Load(bool throwOnError = true, string filePath = ".env", Encoding encoding = null)
{
var initialized = Interlocked.CompareExchange(ref _initialized, 1, 0);
if (initialized > 0)
{
return;
}
// if configured to throw errors then throw otherwise return
if (!File.Exists(filePath))
{
if (throwOnError)
{
throw new FileNotFoundException(
$"An enviroment file with path \"{filePath}\" does not exist.");
}
return;
}
if (encoding == null)
{
encoding = Encoding.Default;
}
// read all lines from the env file
var dotEnvContents = File.ReadAllText(filePath, encoding);
// split the long string into an array of rows
var lines = dotEnvContents.Split(
new[] { "\n", "\r\n", Environment.NewLine },
StringSplitOptions.RemoveEmptyEntries);
// loop through rows, split into key and value then add to enviroment
foreach (var line in lines)
{
var envLine = line.Trim();
if (envLine.StartsWith("#"))
continue;
var index = envLine.IndexOf("=", StringComparison.Ordinal);
if (index < 0)
{
continue;
}
var key = envLine.Substring(0, index).Trim();
if (key.Length == 0)
{
continue;
}
var value = envLine.Substring(index + 1, envLine.Length - (index + 1)).Trim();
if (value.Length == 0)
{
Environment.SetEnvironmentVariable(key, null);
continue;
}
if (value[0] == '\"' || value[0] == '\'')
{
value = value.Trim('\"', '\'');
}
Environment.SetEnvironmentVariable(key, value);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment