2
0

EmbeddedAssembly.cs 2.5 KB

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