1

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

4

1 回答 1

4

使用 ILSpy,您可以在树视图中选择一个装配节点,然后使用 File > Save Code 将结果保存到磁盘。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();
}
于 2019-07-25T00:26:17.223 回答