【问题标题】:Could not load file or assembly error on GetTypes method无法在 GetTypes 方法上加载文件或程序集错误
【发布时间】:2013-12-16 07:14:08
【问题描述】:

我正在从文件夹中读取 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>\bin\Debug\Diagrammer.vshost.exe.Config
LOG: Using host configuration file: 
LOG: Using machine configuration file from C:\Windows\Microsoft.NET\Framework\v4.0.30319\config\machine.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.
}

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

【问题讨论】:

  • 你试过Assembly.LoadAssembly.LoadFrom吗?
  • 我使用的是 LoadFile api。感谢您的参考,LoadFrom 正在运行。
  • 你应该把它作为答案。这可能对处于我这种情况的其他人有所帮助。我会尝试在此基础上发表我的看法。

标签: c# .net dll reflection .net-assembly


【解决方案1】:

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

加载源上下文允许从未包含在探测中的路径加载程序集,但允许找到并加载对该路径的依赖项,因为路径信息由上下文维护。

示例代码

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

【讨论】:

  • 为什么LoadFrom 不抱怨依赖关系?它是如何工作的?
  • 根据阅读 MSDN 编辑了我的答案。希望这会让你满意。
  • 您节省了我的工作日,谢谢!我使用 Assembly.LoadFile() 加载程序集,导致 OP 描述的异常。
  • @AlexandervanTrijffel 感谢您的友好评论。
  • 头撞到这个,不完全确定这两个调用之间的区别,但简单地更改为 LoadFrom 让我的代码再次移动。
猜你喜欢
  • 2010-10-07
  • 2023-03-05
  • 1970-01-01
  • 2013-02-23
  • 2015-09-25
  • 2016-12-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多