7

My scenario: I want to write in log file part of code where exception has happened (for example 5 lines before and 5 lines after line where exception happened - or at least all the code of that method).

My idea is to decompile pdb file in C# code and from that decompiled file find a method that went in exception in catch block.

Pbd file exists and my app is build as debug version. I know that there are tools that allows through its GUI (for example Reflector) to do decompiling but I want to have that functionality from my code.

How to do it?

Mrchief
  • 75,126
  • 20
  • 142
  • 189
Bero
  • 229
  • 1
  • 3
  • 16
  • 1
    The CLR already uses the .pdb file. That's what produces the source code and line number annotations in the exception's StackTrace. Compare to the stack trace you get without the .pdb file in place to see there difference. There's no point in looking for more, that's what is possible. – Hans Passant Jul 04 '11 at 23:57

3 Answers3

5

The PDB contains the mapping between MSIL and source filename / line number. This is most useful when you can go back and look at the original source files, because decompilation typically doesn't preserve line numbers (although it could if it also used the PDB file). It certainly doesn't recover the original code exactly as written, although with symbol names (also stored in the PDB) it often comes close.

Ben Voigt
  • 277,958
  • 43
  • 419
  • 720
2

Look into the source-code of ILSpy. It's an open source alternative for Reflector.

In particular it uses the libraries Mono.Cecil and Mono.Cecil.Pdb. I suspect the latter can help you with what you want to do.

The relevant code parts use the MIT license, which is a permissive license.

CodesInChaos
  • 106,488
  • 23
  • 218
  • 262
-1

Use reflection to get the source code of executing method: System.Reflection.MethodBase.GetCurrentMethod().GetMethodBody();

There is a variety of info you can get using MethodBase members: http://msdn.microsoft.com/en-us/library/system.reflection.methodbase_methods.aspx

Also look in here for some good example for getting MethodBase info while exception handling : http://msdn.microsoft.com/en-us/library/system.reflection.methodbase.getmethodbody.aspx#Y563

Mrchief
  • 75,126
  • 20
  • 142
  • 189