N
N
NBN2016-03-14 00:50:05
Mono
NBN, 2016-03-14 00:50:05

How to copy IL code from one assembly to another using Mono.Cecil?

There is a mixed-mode .NET assembly. I don't care about the native code, and I want to copy the IL code into a new assembly without it (native code) using Mono.Cecil.
Here is my code:

ModuleDefinition module = ModuleDefinition.ReadModule(fileName);
                var name = new AssemblyNameDefinition(module.Assembly.FullName, new Version(1, 0, 0, 0));
                var asm = AssemblyDefinition.CreateAssembly(name, "greeter.exe", ModuleKind.Windows);

                foreach (TypeDefinition type in module.Types)
                {
                    asm.MainModule.Types.Add(type);
                    foreach (MethodDefinition method in type.Methods)
                    {
                        type.Methods.Add(method);
                    }
                }
                asm.EntryPoint = module.Assembly.EntryPoint;
                asm.Write(saveFileDialog1.FileName);

But it throws an exception: Type already attached. What am I doing wrong? Maybe there is some ready-made solution?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Zabodalov, 2020-01-16
@zabbius

Just like that - nothing. There is this https://github.com/gluck/il-repack, it is just about this task

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question