EmbeddedAssembly.cs 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Reflection;
  5. using System.Security.Cryptography;
  6. namespace Optimizer
  7. {
  8. internal sealed class EmbeddedAssembly
  9. {
  10. static Dictionary<string, Assembly> _dictionary;
  11. internal static void Load(string embeddedResource, string fileName)
  12. {
  13. if (_dictionary == null) _dictionary = new Dictionary<string, Assembly>();
  14. byte[] bytes = null;
  15. Assembly assembly = null;
  16. Assembly currentAssembly = Assembly.GetExecutingAssembly();
  17. using (Stream stream = currentAssembly.GetManifestResourceStream(embeddedResource))
  18. {
  19. if (stream == null) throw new Exception($"{embeddedResource} is not found in Embedded Resources.");
  20. bytes = new byte[(int)stream.Length];
  21. stream.Read(bytes, 0, (int)stream.Length);
  22. try
  23. {
  24. assembly = Assembly.Load(bytes);
  25. _dictionary.Add(assembly.FullName, assembly);
  26. return;
  27. }
  28. catch (Exception ex)
  29. {
  30. Logger.LogError("EmbeddedAssembly.Load", ex.Message, ex.StackTrace);
  31. }
  32. }
  33. bool fileOk = false;
  34. string tempFile = string.Empty;
  35. using (SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider())
  36. {
  37. string fileHash = BitConverter.ToString(sha1.ComputeHash(bytes)).Replace("-", string.Empty);
  38. tempFile = Path.GetTempPath() + fileName;
  39. if (File.Exists(tempFile))
  40. {
  41. byte[] byteArray = File.ReadAllBytes(tempFile);
  42. string fileHash2 = BitConverter.ToString(sha1.ComputeHash(byteArray)).Replace("-", string.Empty);
  43. if (fileHash == fileHash2)
  44. {
  45. fileOk = true;
  46. }
  47. }
  48. else
  49. {
  50. fileOk = false;
  51. }
  52. }
  53. if (!fileOk)
  54. {
  55. File.WriteAllBytes(tempFile, bytes);
  56. }
  57. assembly = Assembly.LoadFile(tempFile);
  58. _dictionary.Add(assembly.FullName, assembly);
  59. }
  60. internal static Assembly Get(string assemblyFullName)
  61. {
  62. if (_dictionary == null || _dictionary.Count == 0) return null;
  63. if (_dictionary.ContainsKey(assemblyFullName)) return _dictionary[assemblyFullName];
  64. return null;
  65. }
  66. }
  67. }