Thomas
Thomas

Reputation: 103

How to write in an file in MSIL code

I have a aspx webpage which uses an assembly mine (which mades a custom authentification). I would like to modify MSIL code (so just with ILDASM/ILASM tools) of my assembly in order to log something in a file.

I have tried to add this at the end of the authentification method of my assembly :

IL_0034:  ldstr      "C:\\path_to_my_website\\log.txt"
IL_0039:  newobj     instance void [mscorlib]System.IO.StreamWriter::.ctor(string)
IL_003e:  stloc.1
IL_003f:  ldloc.1
IL_0040:  ldstr      "test"
IL_0045:  callvirt   instance void [mscorlib]System.IO.TextWriter::Write(string)
IL_004a:  nop
IL_004b:  ldloc.1
IL_004c:  callvirt   instance void [mscorlib]System.IO.TextWriter::Close()
IL_0051:  nop

ILASM does not find any error, and the CLR does not throw any exception at runtime, but the file is not created or modified ! :(

Any idea ?

Upvotes: 3

Views: 586

Answers (2)

kvb
kvb

Reputation: 55195

A few thoughts:

  • if you literally added that IL to the very end of the method, then it will all be after a ret instruction (or other unreachable location), so nothing will happen (and the IL probably won't be valid either). Have you tried running peverify on your assembly to make sure that it's valid?
  • is there any reason that the authentication code might not be run? What happens if you try to step through the code in a debugger?

Upvotes: 1

Doug T.
Doug T.

Reputation: 65649

Check out Mono.Cecil. Its intended for loading assemblies as files, mucking with their contents, and saving the results. Specifically this example adds debug tracing to methods of an existing assembly.

Upvotes: 2

Related Questions