我想在我的程序集中反编译一个方法,该方法参考例如'Microsoft.SharePoint.dll',但我没有在计算机上安装SharePoint。 如果我使用下面的代码,我得到一个Mono.Cecil.AssemblyResolutionException'无法解析程序集Microsoft.SharePoint ...'。
AssemblyDefinition assembly = AssemblyDefinition.ReadAssembly("PathToMyAssembly");
ICSharpCode.Decompiler.DecompilerContext context = new ICSharpCode.Decompiler.DecompilerContext(assembly.MainModule);
AstBuilder decompiler = new AstBuilder(context);
decompiler.AddMethod(method); <!-- here it crashes -->
使用ILSpy GUI,我可以无错误地加载我的程序集(在没有SharePoint的同一台机器上)。
我需要在代码中更改哪些内容?
答案 0 :(得分:4)
我自己找到了解决方案。我创建了自己的AssemblyResolver,它捕获AssemblyResolutionException并为缺少引用的程序集返回null。
public class MyDefaultAssemblyResolver : DefaultAssemblyResolver
{
public override AssemblyDefinition Resolve(AssemblyNameReference name)
{
try
{
return base.Resolve(name);
}
catch { }
return null;
}
public override AssemblyDefinition Resolve(AssemblyNameReference name, ReaderParameters parameters)
{
try
{
return base.Resolve(name, parameters);
}
catch { }
return null;
}
public override AssemblyDefinition Resolve(string fullName)
{
try
{
return base.Resolve(fullName);
}
catch { }
return null;
}
public override AssemblyDefinition Resolve(string fullName, ReaderParameters parameters)
{
try
{
return base.Resolve(fullName, parameters);
}
catch { }
return null;
}
}
然后我用它
var resolver = new MyDefaultAssemblyResolver();
resolver.AddSearchDirectory("FolderOfMyAssembly");
var parameters = new ReaderParameters
{
AssemblyResolver = resolver,
};
AssemblyDefinition assembly = AssemblyDefinition.ReadAssembly("PathToMyAssembly", parameters);
我通过调试ILSpy GUI找到了解决方案(幸运的是源代码可用)。