无法在GetTypes方法上加载文件或程序集错误加载、错误、文件、程序

2023-09-04 01:49:21 作者:阳光丶迷离了谁的瞳孔

我正在从文件夹中读取dll和进程类型。

xxx.dll
xxx.interfaces.dll

当我加载xxx.dll并对该程序集调用GetTypes时,它引发异常...

{System.IO.FileNotFoundException: Could not load file or assembly 'xxx.Interfaces, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified.
File name: 'xxx.Interfaces, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'

=== Pre-bind state information ===
LOG: User = xxx
LOG: DisplayName = xxx.Interfaces, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
 (Fully-specified)
LOG: Appbase = file:///<myapp>/bin/Debug/
LOG: Initial PrivatePath = NULL
Calling assembly : (Unknown).
===
LOG: This bind starts in default load context.
LOG: Using application configuration file: <myapp>inDebugDiagrammer.vshost.exe.Config
LOG: Using host configuration file: 
LOG: Using machine configuration file from C:WindowsMicrosoft.NETFrameworkv4.0.30319configmachine.config.
LOG: Policy not being applied to reference at this time (private, custom, partial, or location-based assembly bind).
LOG: The same bind was seen before, and was failed with hr = 0x80070002.
}
C 调试运行的时候出错 提示 未能加载文件或程序集 xxx 或它的某一个依赖项

它似乎正在尝试从启动应用程序路径获取依赖的DLL,而不是正在加载的程序集。当我检查加载和处理程序集xxx.Interfaces.dll时,它工作正常。

推荐答案

尝试使用Assembly.Load()或Assembly.LoadFrom()。LoadFrom()不应抱怨可能由此事实引起的依赖关系

Load-From上下文允许从探测中未包括的路径加载程序集,但允许查找并加载该路径上的依赖项,因为路径信息由上下文维护。

示例代码

var assembly = Assembly.LoadFrom(assemblyPath);
var availableTypes = assembly.GetTypes();