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

时间:2019-07-04 18:57:20

标签: c# decompiling cil decompiler ilspy

我需要将整个IL代码或反编译的源代码获取到文本文件。 ILSpy反编译引擎ICSharpCode.Decompiler是否可以实现?

1 个答案:

答案 0 :(得分:0)

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


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

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

有关反编译器API的更高级用法,请参见ICSharpCode.Decompiler.Console项目。 该控制台项目中带有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();
}
相关问题