Skip to content

Instantly share code, notes, and snippets.

Created January 31, 2021 14:52
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
Modifying self with dnlib
dlroW olleH
using dnlib.DotNet;
using dnlib.DotNet.Emit;
using System;
using System.IO;
using System.Linq;
using System.Reflection;
namespace ConsoleApp1
class Program
static void Main(string[] args)
// Load ourself
var module = ModuleDefMD.Load(typeof(Program).Module);
// Get method definition of PrintStuff()
var method = module.Types
.FirstOrDefault(t => t.Name == "Program")
.FirstOrDefault(m => m.Name == "PrintStuff");
// Overwrite the "Hello World" string
method.Body.Instructions.FirstOrDefault(i => i.OpCode == OpCodes.Ldstr).Operand = "dlroW olleH";
byte[] newAssembly;
// Output modified assembly to byte[]
using (var ms = new MemoryStream())
newAssembly = ms.ToArray();
// Load new byte[]
var asm = Assembly.Load(newAssembly);
// Invoke the now modified PrintStuff method
asm.GetType("ConsoleApp1.Program").InvokeMember("PrintStuff", BindingFlags.InvokeMethod | BindingFlags.NonPublic | BindingFlags.Static, null, null, null);
static void PrintStuff()
Console.WriteLine("Hello World");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment