简体   繁体   English

如何反编译pdb得到C#源代码?

[英]How to decompile pdb to get C# source code?

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).我的场景:我想在日志文件中写入发生异常的部分代码(例如,发生异常的前 5 行和后 5 行 - 或者至少是该方法的所有代码)。

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.我的想法是在 C# 代码中反编译 pdb 文件,并从该反编译文件中找到一个在 catch 块中出现异常的方法。

Pbd file exists and my app is build as debug version. Pbd 文件存在,我的应用程序构建为调试版本。 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.我知道有一些工具允许通过其 GUI(例如 Reflector)进行反编译,但我想从我的代码中获得该功能。

How to do it?怎么做?

The PDB contains the mapping between MSIL and source filename / line number. PDB 包含 MSIL 和源文件名/行号之间的映射。 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).当您可以返回 go 并查看原始源文件时,这是最有用的,因为反编译通常不会保留行号(尽管如果它也使用 PDB 文件则可以)。 It certainly doesn't recover the original code exactly as written, although with symbol names (also stored in the PDB) it often comes close.它当然不会完全按照所写的方式恢复原始代码,尽管使用符号名称(也存储在 PDB 中)它通常很接近。

Look into the source-code of ILSpy.查看 ILSpy 的源代码。 It's an open source alternative for Reflector.它是 Reflector 的开源替代品。

In particular it uses the libraries Mono.Cecil and Mono.Cecil.Pdb .特别是它使用库Mono.CecilMono.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.相关代码部分使用 MIT 许可证,这是一个许可许可证。

Use reflection to get the source code of executing method: System.Reflection.MethodBase.GetCurrentMethod().GetMethodBody();使用反射获取执行方法的源码: 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您可以使用 MethodBase 成员获得各种信息: 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还可以在这里查看一些在异常处理时获取 MethodBase 信息的好例子: http://msdn.microsoft.com/en-us/library/system.reflection.methodbase.getmethodbody.aspx#Y563

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM