我认为您不能使用 .NET Framework 内置函数来执行此操作,因为它们依赖于物理文件。但是,有一个使用Mono Cecil库的解决方案,因为它具有将 Stream 作为输入而不是其符号读取器的文件路径的重载。
下面是一个名为“TestPdb”的控制台应用程序示例,它将其 IL 代码转储到控制台,包括 PDB 信息:
using System;
using System.IO;
using Mono.Cecil;
using Mono.Cecil.Cil;
using Mono.Cecil.Pdb;
namespace TestPdb
{
class Program
{
static void Main(string[] args)
{
// we use a Stream for the assembly
AssemblyDefinition asm;
using (FileStream asmStream = new FileStream("testpdb.exe", FileMode.Open, FileAccess.Read, FileShare.Read))
{
asm = AssemblyDefinition.ReadAssembly(asmStream);
}
// we use a Stream for the PDB
using (FileStream symbolStream = new FileStream("testpdb.pdb", FileMode.Open, FileAccess.Read, FileShare.Read))
{
asm.MainModule.ReadSymbols(new PdbReaderProvider().GetSymbolReader(asm.MainModule, symbolStream));
}
TypeDefinition type = asm.MainModule.GetType("TestPdb.Program");
foreach (MethodDefinition method in type.Methods)
{
Console.WriteLine("Method:" + method.Name);
foreach (Instruction ins in method.Body.Instructions)
{
Console.WriteLine(" " + ins);
if (ins.SequencePoint != null)
{
Console.WriteLine(" Url:" + ins.SequencePoint.Document.Url);
// see http://blogs.msdn.com/b/jmstall/archive/2005/06/19/feefee-sequencepoints.aspx
if (ins.SequencePoint.StartLine != 0xFEEFEE)
{
Console.WriteLine(" StartLine:" + ins.SequencePoint.StartLine + " StartColumn:" + ins.SequencePoint.StartColumn);
Console.WriteLine(" EndLine:" + ins.SequencePoint.EndLine + " EndColumn:" + ins.SequencePoint.EndColumn);
}
// etc...
}
}
}
}
}
}
注意:由于您只需要从 PDB 中读取,您可以重新编译定义 READ_ONLY 条件符号的 Cecil 库以节省一些字节。您还可以将 Cecil 源代码直接嵌入到您的程序集中,无需使用 .DLL 版本。