|
| 1 | +using System.Diagnostics; |
| 2 | +using System.Reflection; |
| 3 | + |
| 4 | +namespace Volatility.Utilities; |
| 5 | + |
| 6 | +public static class EnvironmentUtilities |
| 7 | +{ |
| 8 | + public enum EnvironmentDirectory |
| 9 | + { |
| 10 | + Executable, |
| 11 | + Tools, |
| 12 | + Data, |
| 13 | + ResourceDB, |
| 14 | + Resources, |
| 15 | + Splicer, |
| 16 | + } |
| 17 | + |
| 18 | + private static readonly IReadOnlyDictionary<EnvironmentDirectory, string[]> _relativePaths |
| 19 | + = new Dictionary<EnvironmentDirectory, string[]> |
| 20 | + { |
| 21 | + [EnvironmentDirectory.Executable] = [], |
| 22 | + [EnvironmentDirectory.Tools] = ["tools"], |
| 23 | + [EnvironmentDirectory.Data] = ["data"], |
| 24 | + [EnvironmentDirectory.ResourceDB] = ["data", "ResourceDB"], |
| 25 | + [EnvironmentDirectory.Resources] = ["data", "Resources"], |
| 26 | + [EnvironmentDirectory.Splicer] = ["data", "Splicer"], |
| 27 | + }; |
| 28 | + |
| 29 | + public static string GetEnvironmentDirectory(EnvironmentDirectory dir) |
| 30 | + { |
| 31 | + var baseDir = GetExecutableDirectory(); |
| 32 | + |
| 33 | + if (!_relativePaths.TryGetValue(dir, out var segments)) |
| 34 | + throw new ArgumentOutOfRangeException(nameof(dir), dir, "Unknown environment directory type!"); |
| 35 | + |
| 36 | + return segments.Length == 0 |
| 37 | + ? baseDir |
| 38 | + : Path.Combine(new[] { baseDir }.Concat(segments).ToArray()); |
| 39 | + } |
| 40 | + |
| 41 | + public static string GetExecutableDirectory() |
| 42 | + { |
| 43 | + string? processPath = null; |
| 44 | + var ppProp = typeof(Environment).GetProperty("ProcessPath", BindingFlags.Static | BindingFlags.Public); |
| 45 | + if (ppProp != null) |
| 46 | + { |
| 47 | + processPath = ppProp.GetValue(null) as string; |
| 48 | + } |
| 49 | + |
| 50 | + if (string.IsNullOrEmpty(processPath) && |
| 51 | + Assembly.GetEntryAssembly()?.Location is string entryLoc && |
| 52 | + !string.IsNullOrEmpty(entryLoc)) |
| 53 | + { |
| 54 | + processPath = entryLoc; |
| 55 | + } |
| 56 | + |
| 57 | + if (string.IsNullOrEmpty(processPath)) |
| 58 | + { |
| 59 | + processPath = Process.GetCurrentProcess().MainModule?.FileName; |
| 60 | + } |
| 61 | + |
| 62 | + if (string.IsNullOrEmpty(processPath)) |
| 63 | + throw new InvalidOperationException("Unable to determine the process executable path."); |
| 64 | + |
| 65 | + var exeDir = Path.GetDirectoryName(processPath); |
| 66 | + if (string.IsNullOrEmpty(exeDir)) |
| 67 | + throw new InvalidOperationException($"Cannot determine directory of executable: {processPath}"); |
| 68 | + |
| 69 | + return exeDir; |
| 70 | + } |
| 71 | +} |
0 commit comments