Last active
July 25, 2019 22:14
-
-
Save claruspeter/be2ab1877e7b4605ecf3392832c65bf7 to your computer and use it in GitHub Desktop.
Dotenv for c#
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.Collections.Generic; | |
using System.IO; | |
using System.Linq; | |
namespace System.IO | |
{ | |
public class DotEnv | |
{ | |
public void LoadEnv() | |
{ | |
LoadEnvIn(Directory.GetCurrentDirectory()); | |
} | |
private void LoadEnvIn(string folder) | |
{ | |
bool fileExists = | |
LoadEnvFileAt(Path.Combine(folder, ".env.development")) | |
|| LoadEnvFileAt(Path.Combine(folder, ".env")); | |
if( !fileExists ){ | |
string parent = Path.GetDirectoryName(folder); | |
if( parent != folder && Directory.Exists(parent)){ | |
LoadEnvIn(parent); | |
} | |
} | |
} | |
private bool LoadEnvFileAt(string filename) | |
{ | |
if (File.Exists(filename)) | |
{ | |
var lines = File.ReadAllLines(filename); | |
var values = | |
lines | |
.Select(CheckLine) | |
.Where(x => x != null) | |
.Select(ParseLine) | |
.Select(LoadIntoEnv) | |
.ToList(); | |
return true; | |
} | |
return false; | |
} | |
private string CheckLine(string line){ | |
string trimmed = line.Split('#')[0].Trim(); | |
if(String.IsNullOrWhiteSpace(trimmed)){ | |
return null; | |
} | |
if(trimmed.IndexOf('=') < 1){ | |
return null; | |
} | |
return trimmed; | |
} | |
private KeyValuePair<string,string> ParseLine(string line){ | |
var splitAt = line.IndexOf('='); | |
return new KeyValuePair<string,string>(line.Substring(0,splitAt), line.Substring(splitAt + 1)); | |
} | |
private KeyValuePair<string,string> LoadIntoEnv(KeyValuePair<string,string> setting){ | |
Environment.SetEnvironmentVariable(setting.Key, setting.Value); | |
return setting; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment