EmbeddedAssembly.cs 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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. public class EmbeddedAssembly
  9. {
  10. private static Dictionary<string, Assembly> dic;
  11. public static void Load(string embeddedResource, string fileName)
  12. {
  13. if (dic == null)
  14. dic = new Dictionary<string, Assembly>();
  15. byte[] ba = null;
  16. Assembly asm = null;
  17. var curAsm = Assembly.GetExecutingAssembly();
  18. using (var stm = curAsm.GetManifestResourceStream(embeddedResource))
  19. {
  20. if (stm == null)
  21. throw new Exception(embeddedResource + " is not found in Embedded Resources.");
  22. ba = new byte[(int)stm.Length];
  23. stm.Read(ba, 0, (int)stm.Length);
  24. try
  25. {
  26. asm = Assembly.Load(ba);
  27. dic.Add(asm.FullName, asm);
  28. return;
  29. }
  30. catch { }
  31. }
  32. var fileOk = false;
  33. var tempFile = "";
  34. using (var sha1 = new SHA1CryptoServiceProvider())
  35. {
  36. var fileHash = BitConverter.ToString(sha1.ComputeHash(ba)).Replace("-", string.Empty);
  37. ;
  38. tempFile = Path.GetTempPath() + fileName;
  39. if (File.Exists(tempFile))
  40. {
  41. var bb = File.ReadAllBytes(tempFile);
  42. var fileHash2 = BitConverter.ToString(sha1.ComputeHash(bb)).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, ba);
  56. }
  57. asm = Assembly.LoadFile(tempFile);
  58. dic.Add(asm.FullName, asm);
  59. }
  60. public static Assembly Get(string assemblyFullName)
  61. {
  62. if (dic == null || dic.Count == 0)
  63. return null;
  64. if (dic.ContainsKey(assemblyFullName))
  65. return dic[assemblyFullName];
  66. return null;
  67. }
  68. }
  69. }