Help and Support

文章编号: 327435 - 最后修改: 2003年8月6日 - 修订: 1.1

PRB:Assembly.LoadFrom 不加载与其位于同一目录的依赖程序集

本页

展开全部 | 关闭全部

症状

如果一个程序集从某个依赖程序集调用一个方法,则可以对该程序集调用 Assembly.LoadFrom() 方法。如果此方法与该程序集位于同一目录中,可能会出现以下异常:
Unhandled Exception:System.Reflection.TargetInvocationException:Exception has been thrown by the target of an invocation.System.IO.FileNotFoundException:File or assembly name assembly, or one of its dependencies, was not found.
当所加载的程序集位于与该程序集同名的目录中,并且调用应用程序在其他目录中时,将出现该问题。

原因

当从与程序集同名的目录(例如,MyAssembly.dll 位于名为 MyAssembly 的目录中)使用 Assembly.LoadFrom() 动态加载程序集时,将在 Load 上下文中加载该程序集,而不是在 LoadFrom 上下文中加载。依赖程序集将不被加载。

解决方案

请重命名从其中加载程序集及该程序集的依赖程序集所在的目录。使用具有其他名称的目录会将该程序集加载到 LoadFrom 上下文中。该程序集的依赖程序集也将被加载。

例如,将 MyAssembly.dll 及其依赖程序集 (DepAssembly.dll) 放在名为 MyAssemblyDir 的目录中,而不是放在名为 MyAssembly 的目录中。

状态

这种现象是设计使然。

更多信息

重现问题的步骤

  1. 创建一个定义某个类的类库。将其命名为 DepAssembly
    //DepAssembly.cs
    using System;
    using System.Reflection;
    
    public class DepAssembly
    {
    }
    					
  2. 创建一个名为 MyAssembly 的类库,然后添加一个对 DepAssembly.dll 的引用。
  3. 添加一个创建 DepAssembly 实例的方法:
    //MyAssembly.cs
    using System;
    using System.Reflection;
    
    public class MyAssembly
    {
    	public void GetDepAssembly()
            { 
               new DepAssembly(); 
            }
    }
    					
  4. 创建一个名为 MyApp 的控制台应用程序,该程序使用 Assembly.LoadFrom() 加载 MyAssembly.dll。使用反射创建一个 MyAssembly 类型,然后调用它的方法:
    //MyApp.cs
    using System;
    using System.Reflection;
    using System.Runtime.Remoting;
    
    class MyApp
    {
    	static void Main()
    	{
    		// Load the assembly and create an Instance of MyAssembly.
    		Assembly aa = Assembly.LoadFrom("MyAssembly\\MyAssembly.dll");
    		Type a_t = aa.GetType("MyAssembly");
    		object o = Activator.CreateInstance(a_t);
    
    		// Invoke the GetDepAssembly method.
    		object ac = o.GetType().InvokeMember("GetDepAssembly", BindingFlags.InvokeMethod, null, o, new object[] {});
    	}
    }
    					
  5. 采用以下目录结构排列已编译的文件:
    \MyApp
    	MyApp.exe
    
    \MyApp\MyAssembly
    	MyAssembly.dll
    	DepAssembly.dll
    						
  6. 运行 MyApp.exe。

    在使用该目录结构时,MyApp.exe 将失败并出现“症状”一节中描述的异常。

参考

有关 Assembly.LoadFrom() 的详细信息,请访问下面的 Microsoft Web 站点:

Assembly.LoadFrom Method (http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfSystemReflectionAssemblyClassLoadFromTopic.asp?frame=true)
有关 .NET 运行时库以及它如何定位程序集的详细信息,请访问下面的 Microsoft Web 站点:

运行时库如何定位程序集 (http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cpconhowruntimelocatesassemblies.asp)

这篇文章中的信息适用于:
  • Microsoft Visual Studio .NET 2002 专业版
关键字:?
kbprb KB327435
Microsoft和/或其各供应商对于为任何目的而在本服务器上发布的文件及有关图形所含信息的适用性,不作任何声明。 所有该等文件及有关图形均"依样"提供,而不带任何性质的保证。Microsoft和/或其各供应商特此声明,对所有与该等信息有关的保证和条件不负任何责任,该等保证和条件包括关于适销性、符合特定用途、所有权和非侵权的所有默示保证和条件。在任何情况下,在由于使用或运行本服务器上的信息所引起的或与该等使用或运行有关的诉讼中,Microsoft和/或其各供应商就因丧失使用、数据或利润所导致的任何特别的、间接的、衍生性的损害或任何因使用而丧失所导致的之损害、数据或利润负任何责任。

文章翻译

 

Related Support Centers