【问题标题】:How to use ICSharpCode.Decompiler to decompile a whole assembly to a text file?如何使用 ICSharpCode.Decompiler 将整个程序集反编译为文本文件?
【发布时间】:2019-07-04 18:57:20
【问题描述】:

我需要将整个 IL 代码或反编译的源代码获取到文本文件中。 ILSpy 反编译引擎 ICSharpCode.Decompiler 有可能吗?

【问题讨论】:

  • 你试过dotpeek吗? jetbrains.com/decompiler
  • 也许 microsoft 的 ilasm 和 ildasm 可以帮助您,它们可以将 il 作为文本和程序集作为二进制文件一起往返。你可以在这里看到一个例子:stackoverflow.com/a/52023423
  • 是的,我研究了 ildasm,但我不确定 ildasm 版本是否应该与框架版本相对应。我的机器上有多个版本的 ildasm。此外,我必须将 ildasm exe 与我的 C# 实现一起“携带”,这会增加一些复杂性。看起来使用 ICSharpCode 会更智能。反编译器,因为它作为 Nuget 包提供。我需要在自定义 C# 应用程序中进行反编译。根本原因是因为我想比较两个 DLL 是否相等.. 不应用版本控制时..
  • 我猜你可以使用github.com/icsharpcode/ILSpy/tree/master/… 作为灵感? (我敢打赌它使用了反编译器)

标签: c# decompiling cil decompiler ilspy


【解决方案1】:

使用 ILSpy,您可以在树视图中选择一个装配节点,然后使用文件 > 保存代码将结果保存到磁盘。 ILSpy 将使用当前选择的语言来执行此操作,因此它既可以反汇编也可以反编译。反编译为 C# 时,保存对话框将包含用于保存 C# 项目 (.csproj) 的选项,每个类都有单独的源代码文件;或整个程序集的单个 C# 文件 (.cs)。


要以编程方式反编译,请使用 ICSharpCode.Decompiler 库(可在 NuGet 上获得)。 例如。将整个程序集反编译为字符串:

var decompiler = new CSharpDecompiler(assemblyFileName, new DecompilerSettings());
string code = decompiler.DecompileWholeModuleAsString();

请参阅ICSharpCode.Decompiler.Console 项目以了解反编译器 API 的更高级用法。 该控制台项目中带有resolver.AddSearchDirectory(path); 的部分可能是相关的,因为反编译器需要找到引用的程序集。


ICSharpCode.Decompiler 库也有一个反汇编 API(更底层):

string code;
using (var peFileStream = new FileStream(sourceFileName, FileMode.Open, FileAccess.Read))
using (var peFile = new PEFile(sourceFileName, peFileStream))
using (var writer = new StringWriter()) {
    var output = new PlainTextOutput(writer);
    ReflectionDisassembler rd = new ReflectionDisassembler(output, CancellationToken.None);
    rd.DetectControlStructure = false;
    rd.WriteAssemblyReferences(peFile.Metadata);
    if (metadata.IsAssembly)
        rd.WriteAssemblyHeader(peFile);
    output.WriteLine();
    rd.WriteModuleHeader(peFile);
    output.WriteLine();
    rd.WriteModuleContents(peFile);

    code = writer.ToString();
}

【讨论】:

  • 这适用于 VS-2013 吗?我试过了,它不兼容..
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-10-13
  • 2011-06-01
  • 1970-01-01
  • 2011-03-28
  • 2020-12-24
相关资源
最近更新 更多