public void StartCilWork() { if (this.asm != null) { foreach (TypeDefinition type in this.asm.MainModule.Types) { if (type.Name != "<Module>") { foreach (MethodDefinition method in type.Methods) { if (this.Filter.Contains(method.Name)) { CilWorker worker = method.Body.CilWorker; string s = string.Concat("Code added in: ", method.Name); // Import StreamWriter constructor. ConstructorInfo ci = typeof(StreamWriter).GetConstructor(new Type[] { typeof(string) }); VariableReference streamw = asm.MainModule.Import(ci); streamw.Name = "sw"; // Get streamw's methods. WriteLine and Flush this.writeLine = streamw.GetType().GetMethod("WriteLine", new Type[] { typeof(string) }); this.flush = streamw.GetType().GetMethod("Flush"); // Create a MSIL instructions. Instruction fileName = worker.Create(OpCodes.Ldstr, "debug-methods.log"); Instruction insertText = worker.Create(OpCodes.Ldstr, s); // Create the streamwriter variable: Instruction createVar = worker.Create(OpCodes.Newobj, streamw); // CIL Instruction for calling StreamWriter.WriteLine() Instruction callWriteLine = worker.Create(OpCodes.Call, this.writeLine); // CIL Instruction for calling StreamWriter.Flush() Instruction callFlush = worker.Create(OpCodes.Call, this.flush); // Get the first instruction of the method. Instruction ins = method.Body.Instructions[0]; // Insert instructions to method body. method.Body.CilWorker.InsertBefore(ins, fileName); worker.InsertAfter(fileName, createVar); worker.InsertAfter(createVar, insertText); worker.InsertAfter(insertText, writeLine); worker.InsertAfter(writeLine, flush); } } } asm.MainModule.Import(type); } // Save the modified assembly. AssemblyFactory.SaveAssembly(this.asm, this.Path); Console.WriteLine("Deep Logging enabled"); } }