如何将程序集对象序列化/反序列化为字节数组

问题描述 投票:4回答:4

假设通过编译代码字符串在内存中创建(可执行)程序集。然后我想将此程序集对象序列化为字节数组,然后将其存储在数据库中。然后我想从数据库中检索字节数组并将字节数组反序列化为一个汇编对象,然后调用程序集的入口点。

起初我只是尝试像.net中的任何其他简单对象一样进行此序列化,但显然不适用于汇编对象。程序集对象包含一个名为GetObjectData的方法,该方法获取重新安装程序集所需的序列化数据。所以我有点困惑的是我如何将这一切拼凑起来用于我的场景。

答案只需要展示如何获取程序集对象,将其转换为字节数组,将其转换回程序集,然后在反序列化程序集上执行入口方法。

c# serialization deserialization system.reflection
4个回答
4
投票

程序集更方便地简单地表示为二进制dll文件。如果你这样想的话,剩下的问题就会消失。特别是,看看Assembly.Load(byte[])从二进制加载Assembly。要将其写为二进制文件,请使用CompileAssemblyFromSource并查看结果的PathToAssembly - 然后使用File.ReadAllBytes(path)从文件中获取二进制文件。


1
投票

使用反射获取汇编字节的脏技巧:

  MethodInfo pi = assembly.GetType().GetMethod("GetRawBytes", BindingFlags.Instance | BindingFlags.NonPublic);
  object o = pi.Invoke(assembly, null);

  byte[] assemblyBytes = (byte[])o;

说明:至少在我的示例中(程序集是从字节数组加载的),程序集实例的类型为“System.Reflection.RuntimeAssembly”。这是一个内部类,因此只能使用反射访问它。 “RuntimeAssembly”有一个方法“GetRawBytes”,它返回汇编字节。


1
投票

这是我的例子:

public static byte[] SerializeAssembly()
{
  var compilerOptions = new Dictionary<string, string> { { "CompilerVersion", "v4.0" } };
  CSharpCodeProvider provider = new CSharpCodeProvider(compilerOptions);

  CompilerParameters parameters = new CompilerParameters()
  {
    GenerateExecutable = false,
    GenerateInMemory = false,
    OutputAssembly = "Examples.dll",
    IncludeDebugInformation = false,
  };
  parameters.ReferencedAssemblies.Add("System.dll");

  ICodeCompiler compiler = provider.CreateCompiler();
  CompilerResults results = compiler.CompileAssemblyFromSource(parameters, StringClassFile());

  return File.ReadAllBytes(results.CompiledAssembly.Location);
}

private static Assembly DeserializeAssembyl(object fromDataReader)
{
  byte[] arr = (byte[])fromDataReader;
  return Assembly.Load(arr);
}



private string StringClassFile()
    {
      return "using System;" +
      "using System.IO;" +
      "using System.Threading;" +
      "namespace Examples" +
      "{" +
      " public class FileCreator" +
      " {" +
      "     private string FolderPath { get; set; }" +
      "     public FileCreator(string folderPath)" +
      "     {" +
      "         this.FolderPath = folderPath;" +
      "     }" +
      "     public void CreateFile(Guid name)" +
      "     {" +
      "         string fileName = string.Format(\"{0}.txt\", name.ToString());" +
      "         string path = Path.Combine(this.FolderPath, fileName);" +
      "         if (!File.Exists(path))" +
      "         {" +
      "             using (StreamWriter sw = File.CreateText(path))" +
      "             {" +
      "                 sw.WriteLine(\"file: {0}\", fileName);" +
      "                 sw.WriteLine(\"Created from thread id: {0}\", Thread.CurrentThread.ManagedThreadId);" +
      "             }" +
      "         }" +
      "         else" +
      "         {" +
      "             throw new Exception(string.Format(\"duplicated file found {0}\", fileName));" +
      "         }" +
      "     }" +
      " }" +
      "}";
    }

0
投票

System.Reflection.AssemblyISerializable,可以简单地序列化如下:

Assembly asm = Assembly.GetExecutingAssembly();
BinaryFormatter formatter = new BinaryFormatter();
MemoryStream stream = new MemoryStream();
formatter.Serialize(stream, asm);

和反序列化同样简单,但改为调用BinaryFormatter.Deserialize

© www.soinside.com 2019 - 2024. All rights reserved.