using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Threading; using EmbedIO.Utilities; namespace EmbedIO.Files { /// /// Provides access to embedded resources to a . /// /// public class ResourceFileProvider : IFileProvider { private readonly DateTime _fileTime = DateTime.UtcNow; /// /// Initializes a new instance of the class. /// /// The assembly where served files are contained as embedded resources. /// A string to prepend to provider-specific paths /// to form the name of a manifest resource in . /// is . public ResourceFileProvider(Assembly assembly, string pathPrefix) { Assembly = Validate.NotNull(nameof(assembly), assembly); PathPrefix = pathPrefix ?? string.Empty; } /// public event Action ResourceChanged { add { } remove { } } /// /// Gets the assembly where served files are contained as embedded resources. /// public Assembly Assembly { get; } /// /// Gets a string that is prepended to provider-specific paths to form the name of a manifest resource in . /// public string PathPrefix { get; } /// public bool IsImmutable => true; /// public void Start(CancellationToken cancellationToken) { } /// public MappedResourceInfo? MapUrlPath(string urlPath, IMimeTypeProvider mimeTypeProvider) { var resourceName = PathPrefix + urlPath.Replace('/', '.'); long size; try { using var stream = Assembly.GetManifestResourceStream(resourceName); if (stream == null || stream == Stream.Null) return null; size = stream.Length; } catch (FileNotFoundException) { return null; } var lastSlashPos = urlPath.LastIndexOf('/'); var name = urlPath.Substring(lastSlashPos + 1); return MappedResourceInfo.ForFile( resourceName, name, _fileTime, size, mimeTypeProvider.GetMimeType(Path.GetExtension(name))); } /// public Stream OpenFile(string path) => Assembly.GetManifestResourceStream(path); /// public IEnumerable GetDirectoryEntries(string path, IMimeTypeProvider mimeTypeProvider) => Enumerable.Empty(); } }