EmbeddedAssembly.cs 2.5 KB

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