我有一个问题,在C#
运行时加载DLL
。
代码:
foreach (var f in Directory.EnumerateFiles(startFolder, "*.dll", SearchOption.AllDirectories))
{
try
{
var assembly = Assembly.LoadFrom(f);
var types = assembly.GetTypes(); //exception raised here
foreach (var type in types)
{
if (type.GetInterface("IPlayerFactory") != null)
instances.Add((IPlayerFactory)Activator.CreateInstance(type));
}
assembly = null;
}
catch (ReflectionTypeLoadException ex) { /* later, keep reading */}
异常表示:
An exception of type 'System.Reflection.ReflectionTypeLoadException' occurred in
mscorlib.dll but was not handled in user code
Additional information: Unable to load one or more of the requested types. Retrieve the
LoaderExceptions property for more information.
我搜索堆栈一点点,发现这个catch
寻找更多的信息(来源:这里)
catch块:
catch (ReflectionTypeLoadException ex)
{
StringBuilder sb = new StringBuilder();
foreach (Exception exSub in ex.LoaderExceptions)
{
sb.AppendLine(exSub.Message);
FileNotFoundException exFileNotFound = exSub as FileNotFoundException;
if (exFileNotFound != null)
{
if (!string.IsNullOrEmpty(exFileNotFound.FusionLog))
{
sb.AppendLine("Fusion Log:");
sb.AppendLine(exFileNotFound.FusionLog);
}
}
sb.AppendLine();
}
string errorMessage = sb.ToString();
//Display or log the error based on your application.
Console.WriteLine(sb);
}
所以我设法提取:
'Battleships.Desktop.vshost.exe' (CLR v4.0.30319: Battleships.Desktop.vshost.exe):
Loaded 'C:SomePathsome_dll.dll'. Cannot find
or open the PDB file.
A first chance exception of type 'System.Reflection.ReflectionTypeLoadException'
occurred in mscorlib.dll
我尝试了一些解决方案,但都不起作用。有什么新想法吗?
在调试模式下构建代码时,将创建两个文件,一个是类库,另一个是'调试数据库' .pdb文件。如果您在调试模式下运行代码,则在反射代码的bin中也包含PDB文件。另一件事是在命令提示符中使用fuslogvw查看Fusion日志。
我收到了相同的神秘错误("无法加载一个或多个请求的类型)。在发布模式下检索LoaderExceptions属性以获取更多信息("),因此amolDotnet的解决方案不适用于我的情况。为了让其他遇到同样问题的人受益,我将指出我通过添加DLL所需的缺失的Nuget包依赖项来设法修复它。我以前在Nuget包控制台中关闭了依赖警告,DLL运行得很好,直到我试图加载程序集。通过反射检查成员。如果krzakov没有提到对Exception信息的深入检查,我可能不会找到这个替代解决方案。