using System; using System.Diagnostics; using System.IO; namespace framework_library { public static class EnvBootstrap { private static bool _loaded; private static string _loadedPath = string.Empty; public static bool IsLoaded => _loaded; public static string LoadedPath => _loadedPath; /// /// Loads variables from a .env file into the current process environment. /// Safe to call multiple times; only the first successful load applies. /// public static void Load(string siteRootPath) { if (_loaded) return; string envFile = ResolveEnvFilePath(siteRootPath); if (string.IsNullOrEmpty(envFile)) { Debug.WriteLine("EnvBootstrap: no .env file found."); return; } LoadFile(envFile); } public static void LoadFile(string envFilePath) { if (_loaded || string.IsNullOrEmpty(envFilePath) || !File.Exists(envFilePath)) return; foreach (string rawLine in File.ReadAllLines(envFilePath)) { string line = rawLine.Trim(); if (line.Length == 0 || line.StartsWith("#")) continue; int separator = line.IndexOf('='); if (separator <= 0) continue; string key = line.Substring(0, separator).Trim(); string value = line.Substring(separator + 1).Trim(); if (value.StartsWith("\"") && value.EndsWith("\"") && value.Length >= 2) value = value.Substring(1, value.Length - 2); else if (value.StartsWith("'") && value.EndsWith("'") && value.Length >= 2) value = value.Substring(1, value.Length - 2); if (key.Length > 0) Environment.SetEnvironmentVariable(key, value, EnvironmentVariableTarget.Process); } _loaded = true; _loadedPath = envFilePath; Debug.WriteLine("EnvBootstrap: loaded " + envFilePath); } private static string ResolveEnvFilePath(string siteRootPath) { string explicitPath = Environment.GetEnvironmentVariable("ENV_FILE"); if (!string.IsNullOrEmpty(explicitPath) && File.Exists(explicitPath)) return Path.GetFullPath(explicitPath); if (!string.IsNullOrEmpty(siteRootPath)) { string siteEnv = Path.Combine(siteRootPath, ".env"); if (File.Exists(siteEnv)) return Path.GetFullPath(siteEnv); } string current = string.IsNullOrEmpty(siteRootPath) ? AppDomain.CurrentDomain.BaseDirectory : siteRootPath; for (int i = 0; i < 6; i++) { if (string.IsNullOrEmpty(current)) break; string candidate = Path.Combine(current, ".env"); if (File.Exists(candidate)) return Path.GetFullPath(candidate); DirectoryInfo parent = Directory.GetParent(current); if (parent == null) break; current = parent.FullName; } return string.Empty; } } }