how to serialize/deserialize an assembly object to and from a byte array

后端 未结 4 830
予麋鹿
予麋鹿 2020-12-18 08:59

Let\'s say a create an (executable) assembly in memory by compiling a code string. Then I want to serialize this assembly object into a byte array and then store it in a da

4条回答
  •  抹茶落季
    2020-12-18 09:43

    A dirty trick to get the assembly bytes using reflection:

      MethodInfo methodGetRawBytes = assembly.GetType().GetMethod("GetRawBytes", BindingFlags.Instance | BindingFlags.NonPublic);
      object o = methodGetRawBytes.Invoke(assembly, null);
      
      byte[] assemblyBytes = (byte[])o;
    

    Explanation: at least in my sample (assembly was loaded from byte array) the assembly instance was of type "System.Reflection.RuntimeAssembly". This is an internal class, so it can be accessed only using reflection. "RuntimeAssembly" has a method "GetRawBytes", which return the assembly bytes.

提交回复
热议问题