-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathDotenv.cs
62 lines (56 loc) · 1.76 KB
/
Dotenv.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
namespace KernelMemory.Extensions.ConsoleTest.Helper;
using System;
using System.Collections.Generic;
using System.IO;
public static class Dotenv
{
private static Dictionary<string, string> envVariables;
static Dotenv()
{
envVariables = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
LoadEnvFile();
}
private static void LoadEnvFile()
{
string? envFilePath = FindEnvFile();
if (envFilePath != null)
{
string[] lines = File.ReadAllLines(envFilePath);
foreach (var line in lines)
{
if (!string.IsNullOrWhiteSpace(line) && !line.StartsWith("#"))
{
int equalsIndex = line.IndexOf('=');
if (equalsIndex > 0)
{
string key = line.Substring(0, equalsIndex).Trim();
string value = line.Substring(equalsIndex + 1).Trim();
envVariables[key] = value;
}
}
}
}
}
private static string? FindEnvFile()
{
string? currentDirectory = Directory.GetCurrentDirectory();
while (currentDirectory != null)
{
string envFilePath = Path.Combine(currentDirectory, ".env");
if (File.Exists(envFilePath))
{
return envFilePath;
}
currentDirectory = Directory.GetParent(currentDirectory)?.FullName;
}
return null;
}
public static string? Get(string key)
{
if (envVariables.ContainsKey(key))
{
return envVariables[key];
}
return null;
}
}