Posted June 29, 20214 yr From an old topic: https://forum.tuts4you.com/topic/42934-c-dnlib-how-do-i-change-const-string/?tab=comments#comment-208456 Source Code Stub file: namespace DlibStub { using System; public static class ConstTester { public const string MYCONST = "1111"; public const string DNTEST = "2222"; public static void GetResult() { Console.WriteLine($"Result: {MYCONST}"); Console.WriteLine($"Result: {DNTEST}"); } } } IL Code: field: System.String DlibStub.ConstTester::DNTEST field: System.String DlibStub.ConstTester::MYCONST Instruction: IL_0000: ldstr "Dnlib Tester" Instruction: IL_0000: ldstr "Result: 1111" Instruction: IL_0005: call System.Void System.Console::set_Title(System.String) Instruction: IL_0005: call System.Void System.Console::WriteLine(System.String) Instruction: IL_000A: call System.Void DlibStub.ConstTester::GetResult() Instruction: IL_000A: ldstr "Result: 2222" Instruction: IL_000F: call System.String System.Console::ReadLine() Instruction: IL_000F: call System.Void System.Console::WriteLine(System.String) Instruction: IL_0014: pop Instruction: IL_0014: ret Instruction: IL_0015: ret Code to replace text: public static void Inizialize(string fileModule) { using var module = ModuleDefMD.Load(fileModule); using var text = File.AppendText("LogDnlib.txt"); // For write to txt foreach (TypeDef type in module.GetTypes()) { foreach (FieldDef field in type.Fields) { text.WriteLine($"Field: {field}"); text.WriteLine($"FieldName: {field.Name}"); text.WriteLine($"Field: {field}"); if (field.HasConstant && field.ElementType.Equals(ElementType.String)) { if (field.Name.String.Contains("MYCONST")) // Find a text named MYCONST { field.Constant.Value = "test1"; } if (field.Name.String.Contains("DNTEST")) // Find a text named DNTEST { field.Constant.Value = "test2"; } } } } module.Write("Patched.exe"); } Result (ScreenShots): How fix? Edited June 29, 20214 yr by r3xq1
June 30, 20214 yr Hey, When you compile the program the Compiler it self replace those "Constants" to their value on method body because its Constant values so you can't really do that on dnlib. Edited June 30, 20214 yr by CursedLand
June 30, 20214 yr Author [Update] I tried replacing both Fields and Ldstr and it worked. foreach (MethodDef method in type.Methods) { if (method.HasBody == false) continue; if (method.Body.HasInstructions) { for (int i = 0; i < method.Body.Instructions.Count; i++) { if (method.Body.Instructions[i].OpCode == OpCodes.Ldstr && method.Body.Instructions[i].Operand.ToString().Contains("1111")) { method.Body.Instructions[i].Operand = "test1"; } if (method.Body.Instructions[i].OpCode == OpCodes.Ldstr && method.Body.Instructions[i].Operand.ToString().Contains("2222")) { method.Body.Instructions[i].Operand = "test2"; } method.Body.SimplifyBranches(); method.Body.OptimizeMacros(); } } }
Create an account or sign in to comment