如何在.NET中添加文件夹集搜索路径在运行时? [英] How to add folder to assembly search path at runtime in .NET?

查看:139
本文介绍了如何在.NET中添加文件夹集搜索路径在运行时?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的DLL是由第三方应用程序,这是我们不能自定义加载。我的组件必须位于其自己的文件夹。我不能把它们放进GAC(我的应用程序要求使用XCOPY部署)。 当根DLL尝试从另一个DLL(在相同的文件夹中)加载资源或类型,装载失败(FileNotFound)。 是否有可能加入其中,我的DLL(从根DLL)位于装配搜索路径编程方式的文件夹?我不能更改应用程序的配置文件。

My DLLs are loaded by a third-party application, which we can not customize. My assemblies have to be located in their own folder. I can not put them into GAC (my application has a requirement to be deployed using XCOPY). When the root DLL tries to load resource or type from another DLL (in the same folder), the loading fails (FileNotFound). Is it possible to add the folder where my DLLs are located to the assembly search path programmatically (from the root DLL)? I am not allowed to change the configuration files of the application.

推荐答案

听起来像是你可以使用AppDomain.AssemblyResolve事件和手动从DLL目录加载的依赖关系。

Sounds like you could use the AppDomain.AssemblyResolve event and manually load the dependencies from your DLL directory.

编辑(从评论):

AppDomain currentDomain = AppDomain.CurrentDomain;
currentDomain.AssemblyResolve += new ResolveEventHandler(LoadFromSameFolder);

static Assembly LoadFromSameFolder(object sender, ResolveEventArgs args)
{
    string folderPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
    string assemblyPath = Path.Combine(folderPath, new AssemblyName(args.Name).Name + ".dll");
    if (File.Exists(assemblyPath) == false) return null;
    Assembly assembly = Assembly.LoadFrom(assemblyPath);
    return assembly;
}

这篇关于如何在.NET中添加文件夹集搜索路径在运行时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆