public Assembly LoadAssembly(string assemblyName) //@"D://MyAssembly.dll"
{
m_assembly = Assembly.LoadFrom(assemblyName);
return m_assembly;
}
如果我在D:中放入“MyAssembly.dll”并将其副本放在“bin”目录中,则该方法将成功执行。但是,我删除其中任何一个,它会抛出异常。消息如下:
无法加载文件或程序集“MyAssembly,Version = 1.0.0.0,Culture = neutral,PublicKeyToken = null”或其依赖项之一。系统找不到指定的文件。
我想加载D:中存在的程序集。为什么我需要同时将其副本放到“bin”目录?
答案 0 :(得分:5)
也许MyAssembly.dll引用了目录中不存在的某些程序集。将所有程序集放在同一目录中。
或者您可以处理AppDomain.CurrentDomain,AssemblyResolve事件以加载所需的程序集
private string asmBase ;
public void LoaddAssembly(string assemblyName)
{
asmBase = System.IO.Path.GetDirectoryName(assemblyName);
AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);
System.Reflection.Assembly asm = System.Reflection.Assembly.Load(System.IO.File.ReadAllBytes(assemblyName));
}
private Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
//This handler is called only when the common language runtime tries to bind to the assembly and fails.
//Retrieve the list of referenced assemblies in an array of AssemblyName.
Assembly MyAssembly, objExecutingAssemblies;
string strTempAssmbPath = "";
objExecutingAssemblies = args.RequestingAssembly;
AssemblyName[] arrReferencedAssmbNames = objExecutingAssemblies.GetReferencedAssemblies();
//Loop through the array of referenced assembly names.
foreach (AssemblyName strAssmbName in arrReferencedAssmbNames)
{
//Check for the assembly names that have raised the "AssemblyResolve" event.
if (strAssmbName.FullName.Substring(0, strAssmbName.FullName.IndexOf(",")) == args.Name.Substring(0, args.Name.IndexOf(",")))
{
//Build the path of the assembly from where it has to be loaded.
strTempAssmbPath = asmBase + "\\" + args.Name.Substring(0, args.Name.IndexOf(",")) + ".dll";
break;
}
}
//Load the assembly from the specified path.
MyAssembly = Assembly.LoadFrom(strTempAssmbPath);
//Return the loaded assembly.
return MyAssembly;
}
答案 1 :(得分:1)
要获得任何特定的例外,您可以尝试这样做:
try
{
return Assembly.LoadFrom(assemblyName);
}
catch (Exception ex)
{
var reflection = ex as ReflectionTypeLoadException;
if (reflection != null)
{
foreach (var exception in reflection.LoaderExceptions)
{
// log / inspect the message
}
return null;
}
}