Pushkar
Pushkar

Reputation: 1360

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

Upvotes: 6

Views: 10370

Answers (2)

Michael Piendl
Michael Piendl

Reputation: 2884

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

Upvotes: 4

Marc Gravell
Marc Gravell

Reputation: 1064244

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

Upvotes: 6

Related Questions