【问题标题】:Could not load file or assembly (BadImageFormatException and FileNotFoundException)无法加载文件或程序集(BadImageFormatException 和 FileNotFoundException)
【发布时间】:2015-09-17 18:56:06
【问题描述】:

我有两个类库 coreplugins 以及一个使用这两个库的 WPF 应用程序。在core 我动态加载plugins 如下:

try
        {
            Assembly assembly = Assembly.LoadFile("plugins.dll");
        }

加载plugins.dll 后,我从core 库中获得了plugins 中实现Node 抽象类的类型,即core 中定义的类。这是我用来开发和可扩展应用程序的场景。 在我的core 库中的某个地方,我需要遍历从plugins 加载的Node 类的所有字段。它适用于所有字段,如 intdouble 和在 plugins 库中定义的其他自定义类。

theList = assembly.GetTypes().ToList().Where(t => t.BaseType == typeof(Node)).ToList();
var fieldInfos = theList[0].GetType().GetRuntimeFields();
foreach (var item in fieldInfos)
        {
            Type type = item.FieldType; 
            // Here I get exception for fields like XYZ that defined in
            // Revit API though for fields like Int and double it works charm
        }

但问题是,在plugins 项目中,我也使用 Revit API,当上述循环到达来自RevitAPI.dll 的字段时,我得到以下异常(我尝试了目标平台 Any 和 x86):

An unhandled exception of type 'System.BadImageFormatException' occurred in mscorlib.dll
Additional information: Could not load file or assembly 'RevitAPI, 
Version=2015.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its 
dependencies. An attempt was made to load a program with an incorrect format.

当我将所有 3 个项目的构建部分中的目标平台更改为 x64 时,我得到了这个异常:

An unhandled exception of type 'System.IO.FileNotFoundException' occurred in mscorlib.dll
Additional information: Could not load file or assembly 'RevitAPI.dll' 
or one of its dependencies. The specified module could not be found.

【问题讨论】:

  • 您是否在 WPF 应用程序 (.exe) 上的加载环上加载 Revit 上的 DLL?
  • @AugustoGoncalves 在我的 WPF 应用程序中,我使用 core 库来加载 plugins.dll,动态使用 Assembly.LoadFile()。而plugins.dll 本身引用了RevitAPI.dll
  • 那将无法工作...您只能在 Revit 中使用 RevitAPI.dll(作为插件)
  • @AugustoGoncalves 感谢您的评论。 Revit 开发人员是否故意通过设置安全权限或类似的方式阻止他人在其他应用程序中使用该 dll?
  • RevitAPI.dll 实际上只是实际实现的一个薄层,而不是库本身,这就是为什么它不能用于 Revit 内部的独立应用程序

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


【解决方案1】:

Revit API DLL(RevitAPI.dll 和 RevitAPIUI.dll)不适合在外部/独立应用程序 (.exe) 上加载。您只能在类库 (.dll) 上使用它们并在 Revit 中作为插件加载。

发生这种情况是因为 API DLL 实际上是实际实现的薄层。因此,您需要运行 Revit 才能使用它们(作为插件)。

如果您需要从 Revit 外部访问 Revit 数据(例如,从外部应用程序或导出到数据库),您可以创建一个插件,在 Revit 上加载,然后从该插件公开您需要的数据。有一些事件可以提供帮助,例如 Idling 事件。

【讨论】:

    【解决方案2】:

    第一个错误 (System.BadImageFormatException) 是因为使用 AnyCPU 平台编译的应用程序是由 Visual Studio 在 x86 模式下运行的。 RevitAPI.dll 是 x64 混合模式程序集,因此无法在 x86 进程中加载​​。

    第二个错误(System.IO.FileNotFoundException)是因为RevitAPI.dll 无法加载其依赖项。您可以通过将输出或工作目录设置为 Revit 的安装目录 (C:\Program Files\Autodesk\Revit Architecture 20xx\) 来解决此问题。或许您也可以 P/Invoke SetDllDirectory 将此目录添加到搜索路径中。

    当然,就像 Augusto 所说,Revit 没有运行,因此大多数调用都会失败。但是您可以使用简单的类,例如 XYZUnitUtils

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-04-22
      • 1970-01-01
      • 2019-12-22
      • 1970-01-01
      • 2021-11-11
      • 2023-04-07
      • 2011-09-29
      • 1970-01-01
      相关资源
      最近更新 更多