是否有可能得到一个加载.NET程序集的内容作为一个字节数组或流?有可能、作为一个、数组、字节

2023-09-06 14:25:51 作者:长发少女待我娶你。

是否有可能得到一个加载.NET程序集的内容作为一个字节数组或流?

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

我需要知道如何实现GetAssemblyAsByteArray功能。

I need to know how to implement the GetAssemblyAsByteArray function.

编辑: 与File.ReadAllBytes)解决方案(不够好,因为组件可能是动态的,没有,我没有(容易)访问源(它是自动生成的,我想preFER不跟踪它)。序列化的评论可能会奏效,但我不知道如何使用它。我的最终目标是要通过组件为/参考选项CSC.EXE,我还以为它的唯一的方式运作组件等效是否是动态的还是不就是所有需要的组件保存到临时文件。

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.

推荐答案

您可以使用:

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

已加载的大会,它将让你一个字节[] ,适合被传递到的 的Assembly.Load(byte []的)

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.

 
精彩推荐