1

I got .net dll (originally, written in C#) which is being updated / released from time to time. There's a small part of code I need to modify inside this dll which suits my usage needs.

I'm able to do these changes every time using dnSpy but I don't like doing it manually every time.

Is there possibility to automate the process of code change inside dll and how can it be done?
Is it easier to convert dll to IL and change IL instructions and then compile it back or should I do full decompile to C# and then recompile it back using Roslyn?

The code I change is always the same and is changed to the same result code.

WhiteAngel
  • 2,594
  • 2
  • 21
  • 35
  • Does the code you want to modify not belong to a public virtual method? – 41686d6564 stands w. Palestine Jun 28 '20 at 09:28
  • You can only extend the DLL code – Vivek Nuna Jun 28 '20 at 09:30
  • Answer should be among https://www.bing.com/search?q=c%23+ildasm+rebuild+assembly+site%3astackoverflow.com. – Alexei Levenkov Jun 28 '20 at 09:56
  • 1
    This really sounds like the wrong approach here. Any *good* approach is going to involve a designed extension point that allows you to inflience the behaviour without needing to decompile anything. Can you not do that here? There *are* monkey-patch tools, but... As for C# vs IL: reverse engineering to proper C# that compiles cleanly is not always reliable or possible. Emphasis: I can't think of any good scenarios that require what you're trying to do. If you were meant to be able to change this: it would be an extension point. The most common reason I see people try: to bypass licensing checks – Marc Gravell Jun 28 '20 at 11:07

1 Answers1

2

A possible solution for what you want to achieve is Mono.Cecil.

With Cecil, you can load existing managed assemblies, browse all the contained types, modify them on the fly and save back to the disk the modified assembly.

This library is being used by tools like coverlet which change the assembly on the fly in order to be able to compute code coverage.

That being said, I highly agree with Marc Gravell comment that at the first glance this seems to be the wrong approach and a change in design would be more appropriate.

Costin
  • 770
  • 7
  • 19
  • 1
    thank you for mentioning Mono.Cecil, I thought it makes decompile only but if it allows to compile back then it worth looking into it for sure! Regarding the design change, there's a problem because author doesn't want to incorporate my changes and I have to add them manually every time I update dependency. – WhiteAngel Jun 28 '20 at 12:03
  • 1
    Yes, you can make the changes persistent by using AssemblyDefinition.Write method. You can find a small example here: https://www.mono-project.com/docs/tools+libraries/libraries/Mono.Cecil/faq/#i-would-like-to-add-some-tracing-functionality-to-an-assembly-i-cant-debug-is-it-possible-using-cecil – Costin Jun 28 '20 at 12:08