EmbeddedAssembly.cs 2.5 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 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 { }
  29. }
  30. bool fileOk = false;
  31. string tempFile = string.Empty;
  32. using (SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider())
  33. {
  34. string fileHash = BitConverter.ToString(sha1.ComputeHash(bytes)).Replace("-", string.Empty);
  35. tempFile = Path.GetTempPath() + fileName;
  36. if (File.Exists(tempFile))
  37. {
  38. byte[] byteArray = File.ReadAllBytes(tempFile);
  39. string fileHash2 = BitConverter.ToString(sha1.ComputeHash(byteArray)).Replace("-", string.Empty);
  40. if (fileHash == fileHash2)
  41. {
  42. fileOk = true;
  43. }
  44. }
  45. else
  46. {
  47. fileOk = false;
  48. }
  49. }
  50. if (!fileOk)
  51. {
  52. File.WriteAllBytes(tempFile, bytes);
  53. }
  54. assembly = Assembly.LoadFile(tempFile);
  55. _dictionary.Add(assembly.FullName, assembly);
  56. }
  57. internal static Assembly Get(string assemblyFullName)
  58. {
  59. if (_dictionary == null || _dictionary.Count == 0) return null;
  60. if (_dictionary.ContainsKey(assemblyFullName)) return _dictionary[assemblyFullName];
  61. return null;
  62. }
  63. }
  64. }