ResourceLoader.cs 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. using System.IO;
  2. using System.Linq;
  3. using System.Reflection;
  4. namespace CefBridgeDataExchange.Tests.Resources
  5. {
  6. internal static class ResourceLoader
  7. {
  8. private static readonly string MyNameSpaceFull = typeof(ResourceLoader).Namespace;
  9. //TODO: add PreRelease conf to debug conditions
  10. #if !DEBUG
  11. private static readonly Dictionary<string, byte[]> _cachedBinResource;
  12. static ResourceLoader()
  13. {
  14. var assembly = Assembly.GetExecutingAssembly();
  15. _cachedBinResource = assembly.GetManifestResourceNames()
  16. .Where(p => p.StartsWith(MyNameSpaceFull))
  17. .ToDictionary(p => p, p => assembly.GetManifestResourceStream(p).ToBytes());
  18. }
  19. #endif
  20. private static byte[] ToBytes(this Stream me)
  21. {
  22. using (var tmp = new MemoryStream())
  23. {
  24. me.CopyTo(tmp);
  25. return tmp.ToArray();
  26. }
  27. }
  28. public static byte[] GetBinResource(string path)
  29. {
  30. #if DEBUG
  31. var localFile = Path.Combine(DebugSupport.ResourcePath, path);
  32. return File.ReadAllBytes(localFile);
  33. #else
  34. var resName = path.Replace("/", ".");
  35. return CachedBinResource.TryGetValue($"{MyNameSpaceFull}.{resName}", out var bin) ? bin : null;
  36. #endif
  37. }
  38. }
  39. }