Can someone tells me how it is possible to embed a file as a resource into an AssemblyBuilder at runtime ? I begin to think it is not possible.
Just a little note about the context. In Rail, we mount into memory an object graph of an assembly, readed by Mono.PEToolkit, and then, after some instrumentation, we emit it using System.Reflection.Emit. So, a resource for us is just a struct containing a string Name, another string FileName, a byte array for the Data, and a ResourceAttribute set to public or private.
The framework doc tells me that there is two ways to deal with resources. Let's take a look. The first one is calling DefineResource on an AssemblyBuilder or a ModuleBuilder. By doing it this way, you get an IResourceWriter, and then, you add Data to it. Why not, this seems pretty obvious. But, if you do it this way, the IResourceWriter is designed for .resources files, for strings localizations. When simply putting a byte array
in it, with a name, and a public attribute, the IResourceWriter implementation will generates extra bytes, and make the resource (remember, a simple file) unreadable.
The next way (according to the doc), is to use the AddResourceFile method from an AssemblyBuilder. Let's try this way. First, it only wants a file on the HDD, no way to set a stream or something else. So I have to write my byte array of data on the disk, I call AddResourceFile, and once the assembly is builded, I delete temporary resources files. Wrong... The resource is only linked, not embedded. And THERE IS NO WAY TO SPECIFY HOW I WANT IT TO BE DONE.
I've looked how Mono mcs deals with resources. It's amazing ! They have to use Reflection on AssemblyBuilder to get a private method called EmbedResource. If the method is not found, it means that the runtime in used is not the Mono one, so it throw an error, Resources can only be embedded using Mono runtime. Sounds weird no ? Notice that it looks to be possible with the .net 2 framework using the DefineManifestResource method of ModuleBuilder, taking a string Name, a Stream of data, and attributes. Can't wait for the new version of the framework.
So I throw the sponge, as we say in France !
Die Wahrheit Ist Irgendwo Da Draussen