| | | 1 | | // ----------------------------------------------------------------------- |
| | | 2 | | // <copyright file="ResourcesHelper.cs" company="Stéphane ANDRE"> |
| | | 3 | | // Copyright (c) Stéphane ANDRE. All rights reserved. |
| | | 4 | | // </copyright> |
| | | 5 | | // ----------------------------------------------------------------------- |
| | | 6 | | |
| | | 7 | | using System; |
| | | 8 | | using System.IO; |
| | | 9 | | using System.Reflection; |
| | | 10 | | |
| | | 11 | | namespace MyNet.Primitives.Helpers; |
| | | 12 | | |
| | | 13 | | /// <summary> |
| | | 14 | | /// Helper class for working with embedded resources in assemblies. |
| | | 15 | | /// </summary> |
| | | 16 | | public static class ResourcesHelper |
| | | 17 | | { |
| | | 18 | | /// <summary> |
| | | 19 | | /// Opens an embedded resource stream from the specified assembly based on a resource name suffix. |
| | | 20 | | /// </summary> |
| | | 21 | | /// <param name="assembly">The assembly containing the embedded resource.</param> |
| | | 22 | | /// <param name="resourceNameSuffix">The suffix of the resource name to match.</param> |
| | | 23 | | /// <param name="comparison">The string comparison type to use when matching the resource name.</param> |
| | | 24 | | /// <returns>A stream representing the embedded resource, or null if not found.</returns> |
| | | 25 | | public static Stream OpenEmbeddedResource( |
| | | 26 | | Assembly assembly, |
| | | 27 | | string resourceNameSuffix, |
| | | 28 | | StringComparison comparison = StringComparison.OrdinalIgnoreCase) |
| | | 29 | | { |
| | 21 | 30 | | ArgumentNullException.ThrowIfNull(assembly); |
| | 18 | 31 | | ArgumentException.ThrowIfNullOrWhiteSpace(resourceNameSuffix); |
| | | 32 | | |
| | 9 | 33 | | string? match = null; |
| | | 34 | | |
| | 36 | 35 | | foreach (var resourceName in assembly.GetManifestResourceNames()) |
| | | 36 | | { |
| | 9 | 37 | | if (!resourceName.EndsWith(resourceNameSuffix, comparison)) |
| | | 38 | | { |
| | | 39 | | continue; |
| | | 40 | | } |
| | | 41 | | |
| | 6 | 42 | | if (match is not null) |
| | | 43 | | { |
| | 0 | 44 | | throw new InvalidOperationException($"Multiple embedded resources match '{resourceNameSuffix}'."); |
| | | 45 | | } |
| | | 46 | | |
| | 6 | 47 | | match = resourceName; |
| | | 48 | | } |
| | | 49 | | |
| | 9 | 50 | | return match is null |
| | 9 | 51 | | ? throw new InvalidOperationException( |
| | 9 | 52 | | $"Embedded resource '{resourceNameSuffix}' not found.") |
| | 9 | 53 | | : assembly.GetManifestResourceStream(match)!; |
| | | 54 | | } |
| | | 55 | | } |
| | | 56 | | |