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

半城伤御伤魂 提交于 2019-12-29 09:22:41

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/2150913/is-it-possible-to-get-the-contents-of-a-loaded-net-assembly-as-a-byte-array-or

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!