views:

48

answers:

2

Is it possible to get the contents of a loaded .net assembly as a byte array or stream?

What I'm trying to do is something similar to (of course the real scenario is much more complex, so just storing the buffer is not an option).

byte[] bytes = GetTheBytes();
Assembly asm = Assembly.Load(bytes);
byte[] bytes2 = GetAssemblyAsByteArray(asm);
Assert.IsTrue(bytes.SequenceEqual(bytes2));

I need to know how to implement the GetAssemblyAsByteArray function.

Edit: The solution with File.ReadAllBytes() is not good enough because the assembly might be dynamic, and no, I don't have (easy) access to the source (it's automatically generated and I'd prefer not to keep track of it). The comment with serialization might work, but I wouldn't know exactly how to use it. My end goal is to pass the assemblies as /reference options to csc.exe, and the only way I have thought of which works equivalently whether assemblies are dynamic or not is to save all needed assemblies to temporary files.

A: 

You can get the file of the assembly and then get the bytes. But my feeling is that is not what you are looking for.

To get the file of the assembly, you can probably use Assembly.GetFile() which returns a FileStream.

Moron
What if it was a dynamic assembly?
Mehrdad Afshari
If you have dynamically created an assembly, then presumably you have the source that created it. Can't you compare that instead?
Andy West
+1  A: 

You can use:

byte[] bytes = File.ReadAllBytes(assembly.Location);

on an already loaded assembly and it will get you a byte[] that is suitable to be passed to Assembly.Load(byte[]).

However, if the assembly was originally loaded using the Load(byte[]) method, its Location property will be an empty string, meaning that this method will not work.

It doesn't look like there is a method of doing what you want for all assemblies. The obvious workaround it to store the original byte[] when you first get it.

adrianbanks
Actually, reading Location of a dynamic assembly will not return an empty string, but will throw. And the web says there's no way to find out whether the assembly is dynamic, so the try/catch is unavoidable in this case prior to .net4.
erikkallen