using System.Collections.Immutable; using System.Reflection; using System.Text.RegularExpressions; namespace Luna.Configuration.Services; public sealed class EmbeddedResourceLoader { private readonly Assembly? assembly = Assembly.GetExecutingAssembly(); public ImmutableHashSet ListResources(string? pattern = null) { if (assembly is null) throw new InvalidOperationException("Unable to determine the entry assembly."); var resourceNames = assembly.GetManifestResourceNames(); if (string.IsNullOrEmpty(pattern)) return resourceNames.ToImmutableHashSet(); var regex = new Regex(Regex.Escape(pattern).Replace("\\*", ".*").Replace("\\?", ".?"), RegexOptions.IgnoreCase); return resourceNames .Where(r => regex.IsMatch(r)) .ToImmutableHashSet(); } public async Task LoadAsync(string name) { if (assembly is null) throw new InvalidOperationException("Unable to determine the entry assembly."); var resourceName = assembly.GetManifestResourceNames().FirstOrDefault(r => r.EndsWith(name, StringComparison.OrdinalIgnoreCase)); if (resourceName == null) throw new FileNotFoundException($"Embedded resource '{name}' not found."); await using var stream = assembly.GetManifestResourceStream(resourceName); if (stream == null) throw new FileNotFoundException($"Unable to load embedded resource '{name}'."); using var reader = new StreamReader(stream); return await reader.ReadToEndAsync(); } }