Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rewrite a method of a .Net DLL

I have an old .NET DLL which I have lost the source code to and I wanted to see if I could change its behavior.

It has a method that takes in a string and returns a string.

I would want to rewrite this method such that I can return

startStr + " test";

I tried .NET reflector but the project it produced has a bunch of strange errors so I cannot recompile it.

I then tried Reflexil, but it only offers assembly level changes.

Is there any way I could rewrite the method in C# and have the DLL use my method instead?

like image 668
jmasterx Avatar asked Feb 16 '23 02:02

jmasterx


2 Answers

Reflexil should be able to handle this for you - you need to switch to IL view in Reflector and then you can go to the method that you want to change, pull up Reflexil and make your changes. This avoids the problems with decompiling the assembly to source code (which never worked for me without errors in Reflector).

If all you want to do is append a string to a string variable, you can just do something like:

// assuming your original string is already on the stack
ldstr " test"
call System.String System.String::Concat ( System.String, System.String )

This will create a new string on the stack with test appended to it. Once you're done with the editing, you can save the assembly back to disk.

If you need something more complicated (like appending a string returned by a function call), you simply need to call the right method and then call Concat() on the two strings on the stack.

If your original method returns a string then wrapping it in a new function in a new assembly may be a better solution, though. I'd only edit the IL if you really need the original assembly to change because - for example - the string returned from the particular method is used within that same assembly and you need other functions in that assembly to see the changed return value.

Note: I used Reflector 6.8.2.5 and Reflexil 1.0 for this - current Reflector / Reflexil may be different. Let me know if you need these files for your changes.

like image 165
xxbbcc Avatar answered Feb 24 '23 04:02

xxbbcc


Have you tried extension methods? Simply add another method to an existing class.

You do this by:

public static class Foo {

   public static String SomeMethod (this Bar bar) {
       return bar.OriginalMethod()+" test";
   }

}

If the original class was Bar.

like image 28
Willem Van Onsem Avatar answered Feb 24 '23 05:02

Willem Van Onsem