組裝成字節 (Assembly to Bytes)


問題描述

組裝成字節 (Assembly to Bytes)

My scenario ‑ I am trying to send a Assembly File from Server to Client (via direct TCP connection). But the major problem is‑ how do I convert this Assembly to bytes to that it can be readily transferred? I used following ‑ 

byte[] dllAsArray;
using (MemoryStream stream = new MemoryStream())
{
    BinaryFormatter formatter = new BinaryFormatter();
    formatter.Serialize(stream,loCompiled.CompiledAssembly);
    dllAsArray = stream.ToArray();
}

But when I use ‑ 

Assembly assembly = Assembly.Load(dllAsArray);

I get an exception ‑ 

  

Could not load file or assembly '165 bytes loaded from Code generator server, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. An attempt was made to load a program with an incorrect format.   Please help!!!

‑‑‑‑‑

參考解法

方法 1:

Wouldn't that just be the raw dll contents, as though you had saved it to disk? i.e. the equivalent of File.ReadAllBytes?

It sounds like the dll is generated ‑ can you save it anywhere? (temp area, memory stream, etc)?

edit Since it seems you are using code‑dom, try using PathToAssembly (on the compiler‑results) and File.ReadAllBytes (or a similar streaming mechanism).

方法 2:

Simply load the File via ReadAllBytes and write via WriteAllBytes. The byte[] could be transfered over the network.

// Transfer to byte[]
byte[] data = System.IO.File.ReadAllBytes(@"C:\ClassLibaryOne.dll");

// Write to file again
File.WriteAllBytes(@"C:\ClassLibaryOne.dll", data);

edit: If you use an AssemblyBuilder to create your dll, you can use .Save(fileName) to persist it to you harddrive before.

AssemblyBuilder a = ...
a.Save("C:\ClassLibaryTwo.dll);

(by PushkarMarc GravellMichael Piendl)

參考文件

  1. Assembly to Bytes (CC BY‑SA 3.0/4.0)

#assemblies #.net #C#






相關問題

Nhận các phương thức giao diện từ một lớp được tải động trong .NET (Getting interface methods from a dynamically loaded class in .NET)

支持超過 2 個版本的項目 (Supporting more then 2 versions of a project)

無法加載混淆程序集 (Cannot load obfuscated assembly)

如何禁止引用 .NET DLL 類庫 (How to forbid a .NET DLL class library to be referenced)

我可以從命令行運行 .NET 程序集的代碼嗎? (Can I run code from a .NET assembly from a command line?)

如何將一個應用程序組裝到另一個應用程序中? (How to use assembly of one application in to another application?)

從程序集中復制 DLL 以進行部署 (Copy DLL From Assembly For Deployment)

是否可以查看程序集的源代碼?如果是,那麼如何? (Is it possible to view source code of assembly? If yes then How?)

組裝成字節 (Assembly to Bytes)

DLL 與程序集 (DLL versus Assembly)

pdb 是否提供有關源文件中類型定義的信息? (Does pdb provide information about type definitions in source files?)

如何在 .NET 程序集中重命名 [空格] 類型 (How can I rename[space] a type in a .NET assembly)







留言討論