Created
December 29, 2018 07:01
-
-
Save gleox/9a1021cb8712e349a5f77d3764647488 to your computer and use it in GitHub Desktop.
DotEnvHelper.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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