I notice that there is a method of System.Reflection.Assembly
, which is Assembly Load(byte[] rawAssembly)
.
I wonder if there is an opposite ope
System.Security.Policy.Hash is able to calculate a Hash regardless of the assembly's location. So we have at least 2 ways to obtain an 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 fake HashAlgorithm implementation:
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());
System.Reflection.Assembly implements ISerializable. Create an instance of BinaryFormatter and call its Serialize method on 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());
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);