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


- MoreLinq maxBy vs LINQ max + where 2022-01-01
- 输入按键事件处理程序 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04