Opposite operation to load an assembly (byte [] rawAssembly)

I noticed that there is a System.Reflection.Assembly method, which is Assembly Load(byte[] rawAssembly) .

I wonder if there is an opposite operation like byte[] Store(Assembly assembly) . If not, how can I convert an assembly object to byte[] to fully invoke Assembly Load(byte[] rawAssembly) in memory without writing the assembly to a file? Thanks!

Comment: the question comes from a situation where I use a third-party library that returns an Assembly instance for me, and I have to use a reflex to call its methods. I do not know how the library creates this assembly object. I'm just wondering if I can save the assembly object in byte [] and reload it using "Load assembly" (byte [] rawAssembly) ". Thank you!

+5
source share
3 answers

System.Security.Policy.Hash can calculate the hash regardless of the place of assembly. Thus, we have at least 2 ways to get the assembly as a byte array:

1) Using reflection:

 var hash = new Hash(assembly); var dllAsArray = (byte[]) hash.GetType() .GetMethod("GetRawData", BindingFlags.Instance | BindingFlags.NonPublic) .Invoke(hash, new object[0]); 

2) Using a false implementation of HashAlgorithm:

 public class GetWholeBodyPseudoHash : HashAlgorithm { protected override void Dispose(bool disposing) { if(disposing) _memoryStream.Dispose(); base.Dispose(disposing); } static GetWholeBodyPseudoHash() { CryptoConfig.AddAlgorithm(typeof(GetWholeBodyPseudoHash), typeof(GetWholeBodyPseudoHash).FullName); } private MemoryStream _memoryStream=new MemoryStream(); public override void Initialize() { _memoryStream.Dispose(); _memoryStream = new MemoryStream(); } protected override void HashCore(byte[] array, int ibStart, int cbSize) { _memoryStream.Write(array, ibStart, cbSize); } protected override byte[] HashFinal() { return _memoryStream.ToArray(); } } ... var bytes = new Hash(yourAssembly).GenerateHash(new GetWholeBodyPseudoHash()); 
+3
source

System.Reflection.Assembly implements ISerializable. Create an instance of BinaryFormatter and call its Serialize method for any stream - MemoryStream, FileStream, etc.

 Assembly yourAssembly; var formatter = new BinaryFormatter(); var ms = new MemoryStream(); formatter.Serialize(ms, yourAssembly); var reloadedAssembly = Assembly.Load(ms.GetBuffer()); 
+2
source

To convert an assembly from AppDomain to byte [], use:

 var pi = assembly.GetType().GetMethod("GetRawBytes", BindingFlags.Instance | BindingFlags.NonPublic); byte[] assemblyBytes = (byte[]) pi.Invoke(assembly, null); 
0
source

Source: https://habr.com/ru/post/1259432/


All Articles