如何使用 ICSharpCode.Decompiler 将整个程序集反编译为文本文件?

Ros*_*rov 3 c# cil decompiling decompiler ilspy

我需要将整个 IL 代码或反编译源代码保存到文本文件中。ILSpy 反编译引擎 ICSharpCode.Decompiler 可以实现这一点吗?

Dan*_*iel 5

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


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

var decompiler = new CSharpDecompiler(assemblyFileName, new DecompilerSettings());
string code = decompiler.DecompileWholeModuleAsString();
Run Code Online (Sandbox Code Playgroud)

请参阅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();
}
Run Code Online (Sandbox Code Playgroud)