Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!!!

like image 399
Pushkar Avatar asked Mar 23 '09 13:03

Pushkar


2 Answers

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).

like image 152
Marc Gravell Avatar answered Oct 13 '22 04:10

Marc Gravell


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);
like image 36
Michael Piendl Avatar answered Oct 13 '22 06:10

Michael Piendl