如何在不同的文件夹中加载程序集
本文关键字:文件夹 加载 程序集 | 更新日期: 2023-09-27 18:04:06
我需要加载DLL和依赖项。在我的数据库中,我已经保存了所有的依赖关系(路径到引用文件)。
。艾凡:
加载DLL:
- id: 1
- 名称:"DummyModule.dll"
依赖性:
- DLL id: 1
- 路径:"C: ' DLL ' ABC.dll"
AssemblyLoader类:
public class AssemblyLoader : MarshalByRefObject
{
public void Load(string path)
{
ValidatePath(path);
Assembly.Load(path);
}
public void LoadFrom(string path)
{
ValidatePath(path);
Assembly.LoadFrom(path);
}
public void LoadBytes(string path)
{
ValidatePath(path);
var b = File.ReadAllBytes(path);
Assembly.Load(b);
}
public Assembly GetAssembly(string assemblyPath)
{
try
{
return Assembly.Load(assemblyPath);
}
catch (Exception ex)
{
throw new InvalidOperationException(ex.Message);
}
}
public Assembly GetAssemblyBytes(string assemblyPath)
{
try
{
var b = File.ReadAllBytes(assemblyPath);
return Assembly.Load(b);
}
catch (Exception ex)
{
throw new InvalidOperationException(ex.Message);
}
}
private void ValidatePath(string path)
{
if (path == null)
throw new ArgumentNullException("path");
if (!File.Exists(path))
throw new ArgumentException(String.Format("path '"{0}'" does not exist", path));
}
}
主类:
static void Main(string[] args)
{
string file1 = @"1'DummyModule.dll";
string file2 = @"2'PSLData.dll";
string file3 = @"3'Security.dll";
try
{
AppDomain myDomain = AppDomain.CreateDomain("MyDomain");
var assemblyLoader = (AssemblyLoader)myDomain.CreateInstanceAndUnwrap(typeof(AssemblyLoader).Assembly.FullName, typeof(AssemblyLoader).FullName);
assemblyLoader.LoadBytes(file2);
assemblyLoader.LoadBytes(file3);
var dummy = assemblyLoader.GetAssemblyBytes(file1);
foreach (var t in dummy.GetTypes())
{
var methodInfo = t.GetMethod("D");
if (methodInfo != null)
{
var obj = Activator.CreateInstance(t);
Console.Write(methodInfo.Invoke(obj, new object[] { }).ToString());
}
}
AppDomain.Unload(myDomain);
}
catch (Exception ex)
{
Console.Write(ex.Message);
}
Console.ReadKey();
}
在上面的代码中,"DummyModule.dll"是主dll,"PSLData.dll"answers"Security.dll"是依赖项。
当我调用我的"DummyModule.dll"的方法"D"时,错误出现:
Could not load file or assembly 'DummyModule, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified.
所有DLL文件仍然在不同的文件夹。我怎么能加载所有需要的文件和调用一个函数?
谢谢。
尝试使用这个…
serviceAgentAssembly =System.Reflection.Assembly.LoadFrom(string.Format(CultureInfo.InvariantCulture, @"{0}'{1}", assemblyPath, assemblyName));
foreach (Type objType in serviceAgentAssembly.GetTypes())
{
//further loops to get the method
//your code to ivoke the function
}
您使用的是程序集的相对路径,所以问题是"相对于什么?"你创建并加载组件的新AppDomain在树林中丢失了;它不继承创建它的AppDomain的相同探测路径。看一下System类。AppDomainSetup及其属性ApplicationBase和PrivateBinPath以及以AppDomainSetup实例作为参数的createddomain()的形式。最简单的解决方案是使用AppDomain.CurrentDomain返回的AppDomainSetup实例。SetupInformation是当前域,当然是创建新域的应用。