3

I can get at the method body easily enough using reflection

Type type = assembly.GetType("Lorem.Ipsum.Dolor.Sit");
MethodInfo methodInfo = type.GetMethod("Amet");
MethodBody methodBody = methodInfo.GetMethodBody();

How can I programatically change the method body and save my changes back to disk?

Hank Gay
  • 70,339
  • 36
  • 160
  • 222
Jeffrey LeCours
  • 1,413
  • 15
  • 21
  • Can you explain what the use of this would be? Why not just write a new method or extension method? – Tejs May 14 '10 at 19:08
  • What is it you're actually trying to accomplish? You can't change the method body with reflection alone. MethodBody only gives you information about the MSIL inside (see doc ) – John Nelson May 14 '10 at 19:10
  • I will be given a path to an assembly, load it, remove all code from the method body (aside from what's needing to satisfy the return type), and save it as a new assembly to disk. I believe that changing the method body will be less error prone than trying to use Assembly/Module/TypeBuilder and Reflection.Emit to try and duplicate the methods for a new, dynamically created assembly. Don't bother asking "why do you want to do this", as I unfortunately can't share (NDA). :( – Jeffrey LeCours May 14 '10 at 19:49

3 Answers3

3

AFAIK, you can't.

With reflection you modified an in-memory object which was produced from a binary loaded and optimized by the CLR at runtime.

EDIT

This question has some more information on this.

Modifying Existing .NET Assemblies

Community
  • 1
  • 1
kervin
  • 11,672
  • 5
  • 42
  • 59
2

One another good lib for this: https://bitbucket.org/0xd4d/dnlib

Handles obfuscated assemblies much better comparing to Mono.Cecil.

focus
  • 31
  • 5
1

you can't do it without third-party libs. take a look at: http://www.mono-project.com/Cecil

Andrey
  • 59,039
  • 12
  • 119
  • 163