如何在.NET 运行时将文件夹添加到程序集搜索路径?

How to add folder to assembly search path at runtime in .NET?(如何在.NET 运行时将文件夹添加到程序集搜索路径?)
本文介绍了如何在.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 运行时将文件夹添加到程序集搜索路径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
quot;Overflowquot; compiler error with -9223372036854775808L(编译器错误-9223372036854775808L(Q;溢出Q))
Visual Studio 2010 ReportViewer Assembly References(Visual Studio 2010 ReportViewer程序集引用)
Weird behaviour when I open a reportviewer in WPF(在WPF中打开报表查看器时出现奇怪的行为)
how do i pass parameters to aspnet reportviewer(如何将参数传递给aspnet report查看器)