中运行时将文件夹添加到程序集搜索路径

中运行时将文件夹添加到程序集搜索路径

本文介绍了如何在 .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)) return null;
    Assembly assembly = Assembly.LoadFrom(assemblyPath);
    return assembly;
}

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

08-31 03:48