Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Open Emitted assembly generated code appears empty in Reflector when it is not.

I'm generating a dynamic assembly using Reflection.Emit which includes a single class. I have a bug which is causing a BadImageException. To resolve this I need to see the compiled code, and therefore I'm saving the dynamic assembly to disk.

I've already tried PEVerify against the assembly which seems to think there are no errors. I now want to view the generated code in Reflector, but the assembly appears as empty (which I know it's not).

Any idea why this is happening?

var assemblyName = new AssemblyName("An.Assembly");
var appDomain = Thread.GetDomain();
var assemblyBuilder = appDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.RunAndSave);
var moduleBuilder = assemblyBuilder.DefineDynamicModule(assemblyName.Name);
var typeBuilder = moduleBuilder.DefineType("MyClass", TypeAttributes.Public | TypeAttributes.Class);
... 
typeBuilder.CreateType();
assemblyBuilder.Save("temp.dll");

By the way I'm already using the Relection.Emit plugin for reflector which doesn't help with this issue.

like image 957
TheCodeKing Avatar asked Oct 18 '10 20:10

TheCodeKing


1 Answers

Replace:

var moduleBuilder = assemblyBuilder.DefineDynamicModule(assemblyName.Name);

With:

var moduleBuilder = assemblyBuilder.DefineDynamicModule(assemblyName.Name, "yourfilename.dll");

Then look for it in your current directory, probably your bin folder. Assemblies and modules are technically two separate entities, and you're only saving the assembly information, not the module information (where all your code lives). (Also, don't name them both with the same filename, of course.)

like image 67
Kirk Woll Avatar answered Oct 13 '22 14:10

Kirk Woll