EmbeddedAssembly.cs 2.6 KB

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