Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
683 views
in Technique[技术] by (71.8m points)

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...