我的场景:
我想在日志文件中写入发生异常的代码部分(例如发生异常的行前 5 行和行后 5 行 - 或者至少是该方法的所有代码)。
我的想法是用 C# 代码反编译 pdb 文件,并从该反编译文件中找到一个在 catch 块中出现异常的方法。
Pbd 文件存在,我的应用程序构建为调试版本。我知道有些工具允许通过其 GUI(例如 Reflector)进行反编译,但我希望从我的代码中获得该功能。
怎么做呢?
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?
发布评论
评论(3)
PDB 包含 MSIL 和源文件名/行号之间的映射。当您可以返回并查看原始源文件时,这是最有用的,因为反编译通常不会保留行号(尽管如果也使用 PDB 文件,则可以保留行号)。它当然不会完全按照编写的方式恢复原始代码,尽管符号名称(也存储在 PDB 中)通常很接近。
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.
查看 ILSpy 的源代码。它是 Reflector 的开源替代品。
特别是,它使用了
Mono.Cecil
和Mono.Cecil.Pdb
库。我怀疑后者可以帮助你做你想做的事。相关代码部分使用MIT许可证,这是一种宽松的许可证。
Look into the source-code of ILSpy. It's an open source alternative for Reflector.
In particular it uses the libraries
Mono.Cecil
andMono.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.
使用反射获取执行方法的源代码:
System.Reflection.MethodBase.GetCurrentMethod().GetMethodBody();
使用 MethodBase 成员可以获取多种信息: http://msdn.microsoft.com/en-us/library/system.reflection.methodbase_methods.aspx
另外,请在此处查看一些在异常处理时获取 MethodBase 信息的好示例:< a href="http://msdn.microsoft.com/en-us/library/system.reflection.methodbase.getmethodbody.aspx#Y563" rel="nofollow">http://msdn.microsoft.com/en-us/library/system.reflection.methodbase.getmethodbody.aspx#Y563
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